2016-12-14 74 views
0
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_wait將阻止兩次。如果執行func_thread1func_thread2中的sem_post s,func_thread3可能會繼續。

但是,它不起作用,除非我在main中添加pthread_join(td3, NULL)。我認爲加入沒有必要,因爲sem_wait可以阻止。

所以pthread_join是必要的,或者我錯誤地使用信號量?

回答

0

pthread_join在您的實施中是強制性的。

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

+0

http://man7.org/linux/man-pages/man3/sem_wait.3.html – Yves

+0

sem_wait()遞減(鎖定)由sem指向的信號量。如果 信號量的值大於零,則減量 繼續,並且函數立即返回。如果信號量 當前具有零值,則呼叫阻塞,直到其可能執行減量(即,信號量值 上升到零以上),或者信號處理器中斷呼叫。 – Yves

+0

您會看到,「如果信號量當前值爲零,則呼叫阻止...」。塊在這裏意味着什麼? – Yves