2017-03-18 8 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; 

    } 

に作成されません作成し、時には2つのスレッド、時には誰が作成されますようのpthreadはスレッドこれは、この出力を返します

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?)が終了しています。時には、スレッドは、OSの状態&負荷に応じて、何かをする時間を持っています。

実際の処理を追加したり、長い遅延や、メインプログラムでスレッド終了を待つためのpthread_join(tdic,NULL);の呼び出しを追加すると、確定的な動作が発生します。

関連する問題