2017-03-18 160 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);等待主程序中的线程终止,您将具有确定性行为。