Are you new? Read the FAQ and catch up on!
4k views

Basic and easy pthread_mutex_lock example (C thread synchronization)

This is an extremely basic example of the usage of the pthread_mutex_lock function.

C
  1. #include <pthread.h>
  2.  
  3. // This variable should be visible to all the threads
  4. pthread_mutex_t mutex;
  5.  
  6. int main (int argc, const char * argv[])
  7. {
  8.   pthread_mutex_init(&mutex, NULL);
  9.  
  10.   [...]
  11.  
  12.   pthread_mutex_destroy(&mutex);
  13. }
  14.  
  15. void lockedFunction()
  16. {
  17.   pthread_mutex_lock(&mutex);
  18.  
  19.   // ... do whatever you need here ...
  20.  
  21.   pthread_mutex_unlock(&mutex);  
  22. }
  23.  

­

Tags: C mutex threads threads synchronization

Embed: