Posted By

msicode on 07/20/16


Tagged

c mutex


Versions (?)

Mutex Threads with C


 / Published in: C
 

These are the basic commands to use Mutex Threads in C

  1. #include <pthread.h>
  2.  
  3. //this is our lock and we use it to lock and unlock our mutex when shared data is accessed.
  4. pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER
  5.  
  6. //the signature of the thread function always looks like this.
  7. void* thread_function(void* arg)
  8. {
  9.  
  10. //before accessing the shared resource
  11.  
  12. pthread_mutex_lock(&lock);
  13.  
  14. //do something access your shared resource
  15.  
  16. pthread_mutex_unlock(&lock);
  17.  
  18. pthread_exit(NULL);
  19.  
  20. }
  21.  
  22. //creating and calling threads
  23.  
  24. int main()
  25. {
  26.  
  27. pthread_t threads[3];
  28. pthread_create(threads[0], NULL, &thread_function, void *arg);
  29. pthread_create(threads[1], NULL, &thread_function, void *arg);
  30. pthread_create(threads[2], NULL, &thread_function, void *arg);
  31.  
  32. //join the threads, join call waits for all threads to finish
  33. int i;
  34.  
  35. for(i = 0; i < 3; i++)
  36. {
  37. pthread_join(threads[i], NULL);
  38. }
  39.  
  40. //after you are finish you should always destroy the thread
  41. pthread_mutex_destory(&lock);
  42.  
  43. }

Report this snippet  

You need to login to post a comment.