2017-03-18 158 views
1
#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include "pthread.h" 
#include "semaphore.h" 

FILE * f; 
sem_t * s1; 
sem_t * s2; 
int check; 
int v1; 
int v2; 
int i; 

static void * client (void *arg){ 


    sem_getvalue(s1, &v1); printf("Client pre wait(S1) in S1 => S1 = %d\n",v1); 
    sem_wait(s1); 
    printf("client works...\n"); 
    check = sem_getvalue(s1, &v1); printf("Client.wait(S1) in S1 => S1 = %d\n",v1); 
    if(check != 0) printf("sem_getvalue error"); 


    return 0; 
    } 


int main(void){ 

    pthread_t tidc; 
    pthread_t tids; 
    int rc; 
    int rs; 

    //Semaforo 1 
    s1 = (sem_t *) malloc(sizeof(sem_t)); 
    check = sem_init (s1, 0, 2); 
    if (check != 0) perror("s1_init failed"); 




    sem_getvalue(s1, &v1); 

    printf("Create the semaphores: S1 = %i\n",v1); 

    sem_wait(s1); 
    printf("main waits\n"); 
    sem_getvalue(s1, &v1); printf("Main.wait(S1) in S1 => S1 = %d\n",v1); 

    rc = pthread_create (&tidc, NULL, client, 0); 
    printf(" thread created ==> rc= %i\n",rc); 


    return 0; 

    } 

它返回的輸出:並行線程創建不創建一個線程

Create the semaphores: S1 = 2 
main waits 
Main.wait(S1) in S1 => S1 = 1 
thread created ==> rc= 0 

,有時候這樣的:

Create the semaphores: S1 = 2 
main waits 
Main.wait(S1) in S1 => S1 = 1 
thread created ==> rc= 0 
Client pre wait(S1) in S1 => S1 = 1 
Client pre wait(S1) in S1 => S1 = 1 
client works... 
Client.wait(S1) in S1 => S1 = Client.wait(S1) in S1 => S1 = 0 

好像有時創建兩個線程,有時甚至沒有之一。我編譯gcc prog.c -lpthred甚至與gcc -pthread prog.c

+0

可能是[主線程退出,還有其他退出嗎?](http://stackoverflow.com/questions/11875956/main-thread-exit-does-other-exit-too) – tofro

回答

0

如果多線程程序不會從一個執行到另一個做同樣的事情,這可能是因爲未初始化變量的(如在非線程程序),也可能是因爲的race condition

在這種情況下,競爭條件在線程執行和程序退出之間。

由於您在創建線程後立即退出主線程,線程將終止(main thread exit, does other exit too?)。有時候,線程有時間做一些事情,具體取決於操作系統狀態&加載。

如果您添加一些實際的處理,長時間延遲或致電pthread_join(tdic,NULL);等待主程序中的線程終止,您將具有確定性行爲。