带C的互斥线程

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了带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. }

以上是关于带C的互斥线程的主要内容,如果未能解决你的问题,请参考以下文章

[C++11 多线程同步] --- 互斥锁

[C++11 多线程同步] --- 互斥锁

C++11多线程 原子操作概念及范例

互斥锁 & 共享锁

C++11/14/17中mutex系列区别

C11线程管理:互斥锁