我写了以下短的应用程序来解决障碍问题。 此应用程序应该保证三个相同的线程运行相同的线程方法,都将在通用代码部分“相遇”。 我跑它,它似乎确定。 我的问题是:屏障为N线程与semphore
1)它是正确的吗?
2)有N个线程实现它的首选和有效的方法吗?
这里是代码:
static sem_t t_1_sem;
static sem_t t_2_sem;
static sem_t t_3_sem;
struct my_thread_info {
int num;
};
void *thread(void *vargp)
{
struct my_thread_info *info = (struct my_thread_info*)vargp;
static int counter=0;
counter++;
if (info->num == 1) {
printf("info->num=%d\n", info->num);
if (counter<3)
sem_wait(&t_1_sem); // down
else {
sem_post(&t_2_sem); // up
sem_post(&t_3_sem); // up
}
} else
if (info->num == 2) {
printf("info->num=%d\n", info->num);
if (counter<3)
sem_wait(&t_2_sem);
else {
printf("info->num=%d\n", info->num);
sem_post(&t_1_sem);
sem_post(&t_3_sem); //up
}
}
else
if (info->num == 3) {
printf("info->num=%d\n", info->num);
if (counter<3)
sem_wait(&t_3_sem);
else {
sem_post(&t_1_sem);
sem_post(&t_2_sem); //up
}
}
printf("meeting occured!\n");
}
int main()
{
pthread_t tid0, tid1, tid2;
struct my_thread_info info1, info2, info3;
info1.num = 1;
sem_init(&t_1_sem, 0, 0);
sem_init(&t_2_sem, 0, 0);
sem_init(&t_3_sem, 0, 0);
pthread_create(&tid0, NULL, thread, &info1);
info2.num = 2;
pthread_create(&tid1, NULL, thread, &info2);
info3.num = 3;
pthread_create(&tid2, NULL, thread, &info3);
pthread_join(tid0, NULL);
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pause();
return 0;
}
问候 凯文
又见pthread_barrier_XXX功能,如果你只需要障碍。 – nos 2013-02-13 16:07:33