我寫了以下短的應用程序來解決障礙問題。 此應用程序應該保證三個相同的線程運行相同的線程方法,都將在通用代碼部分「相遇」。 我跑它,它似乎確定。 我的問題是:屏障爲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