c - C 基本打印中的 Pthread

标签 c multithreading pthreads pthread-join

我正在使用创建子线程的 Pthreads 编写 C 程序。创建子线程后,父线程应该输出两条消息:“parent:begin”然​​后打印“parent:done”。子线程“child:begin”和“child:done”也是如此。我必须确保主线程在生成的(子)线程之前打印出他的第二条消息。我必须遵循实现,但它只会以错误的顺序打印。我想我应该使用标志。任何帮助将不胜感激。

#include <unistd.h>
#include <stdio.h>
#include <pthread.h>


volatile int done = 0;

void *child(void *arg) {
 printf("child\n");
done = 1;
 printf("child:done");
return NULL;
 }

int main(int argc, char *argv[]) {
 printf("parent: begin\n");
 pthread_t c;
 pthread_create(&c, NULL, child, NULL); // create child
 while (done == 0); // spin
 printf("parent: end\n");
 return 0;
 }

最佳答案

如果您想让父线程先打印done,那么您应该让子线程自旋直到父线程完成。 (现在父线程正在等待子线程。)您还应该使用 pthread_join 来确保子线程在主线程返回之前完成:

#include <unistd.h>
#include <stdio.h>
#include <pthread.h>


volatile int done = 0;

void *child(void *arg) {
    printf("child: begin\n");
    while (done == 0); // spin
    printf("child: done\n");
    return NULL;
}

int main(int argc, char *argv[]) {
    printf("parent: begin\n");
    pthread_t c;
    pthread_create(&c, NULL, child, NULL); // create child
    printf("parent: done\n");
    done = 1;
    pthread_join(c, NULL);
    return 0;
}

在我的机器上我得到这个输出:

parent: begin
parent: done
child: begin
child: done

关于c - C 基本打印中的 Pthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35119313/

相关文章:

c - 在 .S 中包含头文件以获得一些结构大小

c# - 线程暂停和恢复

c - 使用 pthreads 进行练习,但我的代码中出现了一些意外行为

c - 让所有的 child 从另一个 child 线程 sleep

c++ - pjsip 新调用错误...无法找到默认音频设备 (PJMEDIA_EAUD_NODEFDEV)

C - 程序只执行 if else 语句的一部分

c++ - 从 gcc 5.4 升级到 gcc 6.3 std::thread std:ref 问题

multithreading - 授予对 std::mutex 的优先访问权

c - 如何提供一系列交错线程来表明代码中断并且没有提供完美的同步?

python - 程序的 Linux 权限问题