2017-02-15 67 views
0

我想使它,以便父進程在子線程執行之前執行。我不確定在哪裏我會錯誤地得到我的程序輸出的訂單。如何執行父befor子線程 - pthreads在c

int status = 0; 

void *print_child(void *arg) 
{ 

    while (status == 0) 
    { 
     printf("Signal hasn't changed..\n"); 
     sleep(1); 

    } 
    printf("The child has started...\n"); 
    printf("The child is done! \n "); 
} 

int main() 
{ 
    pthread_t child; 
    pthread_create(&child, NULL, &print_child, NULL); 

    sleep(2); 
    printf("The parent has started...\n"); 
    printf("The parent is done! \n"); 

    status++; 

    if (pthread_join(child, NULL)) 
    { 
     printf("ERROR"); 
     exit(1); 
    } 
} 

OUTPUT:

signal has changed 
signal has changed 
parent has started 
parent is done 
child has started 
child is done 
+3

如果您想要按順序執行操作,爲什麼要使用線程呢?線程是爲了並行完成的事情。 –

+1

你設置父母睡覺,而孩子正在運行,所以... – LPs

+1

@DarkFalcon它聞起來像學校作業 – LPs

回答

1

排除併發執行的最簡單的方法是鎖。在調用pthread_create之前,讓「父母」(原始線程)進行鎖定,並且只有在準備好「子」(新線程)才能運行時纔將其解鎖。 「孩子」應該在做任何事情之前先取鎖。它可以立即解鎖它,如果它想,或保持它來控制訪問共享狀態。