在多线程程序中使用pthread互斥锁

时间:2013-08-25 11:19:49

标签: c linux multithreading thread-synchronization

我正在开发一个创建三个线程的代码。现在使用pthread_mutex我如何同步它们? 假设我有这种类型的代码: -

#include<stdio.h>
#include<pthread.h>

void *function1(void *ptr)
{

   do something on a buffer;
}

void *function2(void *ptr)
{
  do samething else but ob the same buffer;
 }

void *function(void *ptr)
{
  do samething else again on buffer;
}


main()
{ 
   pthread_t t1,t2,t3);
   int a,b,c;
   a= creates a thread using pthread_create(&t1,NULL,func1,NULL);
   b= creates a thread using pthread_create(&t2,NULL,func2,NULL);
   c= creates a thread using pthread_create(&t3,NULL,func1,NULL);

 and after that pthread_join wait till all the threads gets finished;
}

但正如你可以看到,当你做这样的事情时,所有线程同时启动,结果不如预期。现在我们如何使用pthread_mutex锁定和解锁相同的缓冲区,以便一次只有一个线程可以工作? 此外,我希望t1先到t2然后再到t3。如何才能完成基本上我必须设置优先级?

1 个答案:

答案 0 :(得分:2)

请参阅此示例:http://sourcecookbook.com/en/recipes/70/basic-and-easy-pthread-mutex-lock-example-c-thread-synchronization

你必须做一些阅读,但这很容易。 您必须声明并初始化互斥锁: pthread_mutex_t myMutex; pthread_mutex_init(&amp; myMutex,NULL);

并使用它:

的pthread_mutex_lock(安培; myMutex);

//在这里使用缓冲区

调用pthread_mutex_unlock(安培; myMutex);

另外不要忘记清理: pthread_mutex_destroy(安培; myMutex);

相关问题