static int res1 = 0;
static int res2 = 0;
static int res3 = 0;

static int counter = 0;
static sem_t sem;



void * func_thread1(void *p)
{
    sleep(2);
    res1 = 1;
    printf("func_thread1\n");
    sem_post(&sem);
    return NULL;
}

void * func_thread2(void *p)
{
    sleep(2);
    res2 = 2;
    printf("func_thread2\n");
    sem_post(&sem);
    return NULL;
}

void * func_thread3(void *p)
{
    sem_wait(&sem);
    sem_wait(&sem);
    res3 = res1 + res2;
    printf("func_thread3\n");
    return NULL;
}




void main()
{
    sem_init(&sem, 0, counter);
    pthread_t pd1, pd2, pd3;
    pthread_create(&pd1, NULL, func_thread1, NULL);
    pthread_create(&pd2, NULL, func_thread2, NULL);
    pthread_create(&pd3, NULL, func_thread3, NULL);

    //pthread_join(pd3, NULL);

    printf("main_thread\n");
    printf("%d", res3);
}


我试图了解信号量的工作原理。
我正在尝试使td3块等待td1td2

我认为sem_wait将阻止两次。如果执行了sem_postfunc_thread1中的func_thread2,则func_thread3可以继续。

但是,除非我在pthread_join(td3, NULL)中添加main,否则它不会起作用。我认为该联接不是必需的,因为sem_wait可以阻止。

所以pthread_join是必需的,还是我使用了信号量不正确?

最佳答案

pthread_join在您的实施中是必需的。

否则,您的过程将完成(即主返回),并且所有任务(即线程)都将在线程3打印任何内容之前被杀死。

关于c - 为什么sem_wait不阻止,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41140538/

10-11 23:01
查看更多