[英]C Pthreads - Parent/Child process
我編寫了一個創建子線程的 C 程序。 創建子線程后,父線程應該輸出兩條消息。 第一個是“我是父母”,第二個是“父母完成了”。 子線程“我是孩子”和“孩子完成了”也應該發生同樣的情況。 但是我想確保,孩子的第二條消息總是在父母的第二條消息之前完成。 我如何在下面的代碼中實現這一點?
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
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);
}
}
一旦一個線程創建,它就會獨立處理,就像一個獨立於主線程的進程。 在您的情況下,您在語句printf("The parent is done! \\n");
之后加入子線程printf("The parent is done! \\n");
. 操作系統不必總是先完成子線程。 因此,您的預期結果可能並不總是滿足。 在語句printf("The parent is done! \\n");
之前放置一個很長的 sleep 語句printf("The parent is done! \\n");
並檢查但仍然沒有必要讓孩子首先完成。
您的代碼不起作用的原因是您沒有確保在子線程中的第二個 printf 之前執行父線程中的第二個 printf 。
在這種情況下,一個不錯的選擇是使用互斥鎖。 在這種情況下,您可以使用互斥鎖在第二個 printf 之前充當“守衛”,因此代碼將如下所示:
pthread_mutex_t print_lock;
...
在 print_child 中:
// can only acquire after the parent releases, therefore guaranteeing that
// the parent thread has already printed the second statement
pthread_mutex_lock(&print_lock);
printf("The child is done! \n ");
pthread_mutex_unlock(&print_lock);
在主要:
// lock it before the child thread is
// started, therefore guaranteeing the parent will have initial ownership
pthread_mutex_lock(&print_lock);
pthread_create(&child, NULL, &print_child, NULL);
sleep(2);
printf("The parent has started...\n");
printf("The parent is done! \n");
pthread_mutex_unlock(&print_lock);
...
只需在printf("The parent has started...\\n");
之后加上以下行printf("The parent has started...\\n");
而在printf("The parent is done! \\n");
:
status++;
if (pthread_join(child, NULL))
{
printf("ERROR");
exit(1);
}
所以更正后的代碼如下:
#include <unistd.h>
#include <stdio.h>
#include <pthread.h>
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");
status++;
if (pthread_join(child, NULL))
{
printf("ERROR");
exit(1);
}
printf("The parent is done! \n");
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.