【发布时间】: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