【发布时间】:2011-08-06 06:00:17
【问题描述】:
我需要使用互斥锁(仅)在 2 个线程之间实现屏障同步。屏障同步是 2 个线程在继续之前会在预定义的步骤相互等待。
我可以使用 seamaphore 来做到这一点,但是 我怎样才能只使用互斥锁来实现这一点。有人提示我需要 2 个互斥体而不是 1 个来执行此操作。
使用 Seamaphore:
#include <pthread.h>
#include <semaphore.h>
using namespace std;
sem_t s1;
sem_t s2;
void* fun1(void* i)
{
cout << "fun1 stage 1" << endl;
cout << "fun1 stage 2" << endl;
cout << "fun1 stage 3" << endl;
sem_post (&s1);
sem_wait (&s2);
cout << "fun1 stage 4" << endl;
}
void* fun2(void* i)
{
cout << "fun2 stage 1" << endl;
cout << "fun2 stage 2" << endl;
// sleep(5);
sem_post (&s2);
sem_wait (&s1);
cout << "fun2 stage 3" << endl;
}
main()
{
sem_init(&s1, 0, 0);
sem_init(&s2, 0, 0);
int value;
sem_getvalue(&s2, &value);
cout << "s2 = " << value << endl;
pthread_t iThreadId;
cout << pthread_create(&iThreadId, NULL, &fun2, NULL) << endl;
// cout << pthread_create(&iThreadId, NULL, &fun2, NULL) << endl;
pthread_create(&iThreadId, NULL, &fun1, NULL);
sleep(10);
}
将上述代码编译为“g++ barrier.cc -lpthread”
【问题讨论】:
-
为什么
fun1()和fun2()不返回void*!
标签: c++ multithreading mutex