首页 > 解决方案 > 如何修改代码使两个线程保持打印同一行,以便终端显示'A'和'B'交错

问题描述

这是我到目前为止的代码:

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

int value = 0;
void *runner(void *param);
int main(){
    int pid;
    pthread_t tid;
    pthread_attr_t attr;
    pid = fork();

    if (pid == 0) {
      pthread_attr_init(&attr);
      pthread_create(&tid,&attr,runner,NULL);
      pthread_join(tid,NULL);
      printf("A: value = %d\n", value);
    }

    else if (pid > 0) {
     wait(NULL);
     printf("B: value = %d\n", value);
    }
}

void *runner(void *param){
    value = 5;
    pthread_exit(0);
}

我已经确定了子进程和父进程,但我不确定如何让 A 和 B 交错打印。

标签: c++pthreads

解决方案


推荐阅读