我编写了以下简短的应用程序来解决障碍问题。此应用程序应保证运行相同线程方法的三个相同线程都将在公共代码部分“相遇”。我运行它,它似乎没问题。我的问题是:
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;
}
问候凯文