我想让它在子线程执行之前执行父进程。我不确定我的错误在哪里得到我的程序正在输出的订单。
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
答案 0 :(得分:1)
排除并发执行的最简单方法是锁定。拥有"父母" (原始主题)在致电pthread_create
之前先取消锁定,只有当它准备好了孩子时才会解锁。 (新线程)要运行。 "孩子"在做任何事之前应该拿锁;然后它可以在需要时立即解锁,或者让它控制对共享状态的访问。