【问题标题】:Using pthread_mutex in a mutli threaded programme [closed]在多线程程序中使用 pthread 互斥锁 [关闭]
【发布时间】:2013-08-25 11:19:49
【问题描述】:

我正在编写一个创建三个线程的代码。现在使用 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。基本上我要设置优先级怎么办?

【问题讨论】:

  • 某事告诉我,如果打开 any 手册或在 Internet 上查找示例,您会发现数以千计的代码示例和解释...
  • 正如@KerrekSB 所说,首先搜索答案,然后提出问题。您的问题非常基础,即使您阅读了 pthread mtexes 的用法,您也会找到答案。
  • 我读到了 pthread_mutex_lock() ,但是当我实现时,输出并不像expexted。我想调用 t1 然后 t2 然后 t3 但是当我编译代码时,顺序是随机的。我怎样才能摆脱这个?

标签: c linux multithreading thread-synchronization


【解决方案1】:

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

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

并使用它:

pthread_mutex_lock(&myMutex);

//这里使用缓冲区

pthread_mutex_unlock(&myMutex);

也不要忘记清理: pthread_mutex_destroy(&myMutex);

【讨论】:

  • 我读到了 pthread_mutex_lock() ,但是当我实现时,输出并不像expexted。我想调用 t1 然后 t2 然后 t3 但是当我编译代码时,顺序是随机的。我怎样才能摆脱这个?
  • @user2714823 你不能。线程尽可能地执行,正如您所说,这是随机的。
  • 在上面的例子中,我希望首先 thread1 完成然后 thread2 和 thread3 。有可能吗?
  • 那你为什么需要线程呢?你可以只调用方法。但是,如果您仍想以顺序方式调用线程(假设出于实验原因),您可以使用 pthread_join 来等待线程终止。基本上你启动 t1,然后用 pthread_join 等待它。然后你启动 t2 并再次使用 pthread_join 等等。
猜你喜欢
  • 2013-08-31
  • 2011-07-24
  • 2011-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-20
  • 1970-01-01
相关资源
最近更新 更多