Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

let's assume for example i have this piece of code

    #include <phtreads.h>

    int var1 ;
    int varn; 
    
    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    
    void *thread1
    {
        //start critical section1
        pthread_mutex_lock(&mutex);
                
          edit var 1
          edit var n
 
       pthread_mutex_unlock(&mutex); 
       //end critical section1
    }
    
    
    void *thread2
    {
       //start critical section2
        pthread_mutex_lock(&mutex);
    
          edit var 1
          edit var n
   
       pthread_mutex_unlock(&mutex); 
     //end critical section2
    }

   

how many variables can i edit in the critical section ? only 1 variable or how many i want?

assume this is pseudo code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
311 views
Welcome To Ask or Share your Answers For Others

1 Answer

A mutex does not lock any variables.

All it does is block threads from proceeding while another one has the mutex locked. The threads are blocked in the pthread_mutex_lock call until the system can grant the lock to thread.

So the number of variables is unlimited, but for your sanity (and your programs correctness) make sure you know what variables require what mutex to be locked.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...