簡體   English   中英

為什么sem_wait不阻止

[英]why doesn't sem_wait block

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將阻塞兩次。 如果執行func_thread1func_thread2中的sem_post ,則func_thread3可以繼續。

但是,除非我在main添加pthread_join(td3, NULL) ,否則它將不起作用。 我認為加入是不必要的,因為sem_wait可以阻止。

所以pthread_join是必需的,還是我使用的信號量不正確?

在您的實現中, pthread_join是必需的。

否則,您的過程將完成(即主返回),並且所有任務(即線程)都將在線程3打印任何內容之前被殺死。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM