gpt4 book ai didi

c - 如何在子线程之前执行父线程 - C中的pthreads

转载 作者:行者123 更新时间:2023-11-30 15:00:13 24 4
gpt4 key购买 nike

我想让父进程在子线程之前执行。我不确定获取程序输出的顺序时哪里出错了。

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 之前获取锁定,并且仅在准备好“子线程”(新线程)运行时才解锁。 “ child ”在做任何事情之前都应该先拿到锁;如果需要,它可以立即解锁它,或者保留它以控制对共享状态的访问。

关于c - 如何在子线程之前执行父线程 - C中的pthreads,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42251168/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com