[英]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.