[英]how to execute parent befor child thread - pthreads in 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);
}
}
輸出:
signal has changed
signal has changed
parent has started
parent is done
child has started
child is done
排除並發執行的最簡單方法是鎖定。 在調用pthread_create
之前,讓“父”(原始線程)進行鎖定,並僅在准備好“子”(新線程)運行時將其解鎖。 “孩子”應該在做任何事情之前先上鎖; 然后,如果需要,它可以立即將其解鎖,或者保留它以控制對共享狀態的訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.