C++ 如何修改代码,使两个线程保持打印同一行,以便终端显示’;A’;和’;B&x2019;交错

C++ 如何修改代码,使两个线程保持打印同一行,以便终端显示’;A’;和’;B&x2019;交错,c++,pthreads,C++,Pthreads,以下是我目前掌握的代码: #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();

以下是我目前掌握的代码:

#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);
}
#包括
#包括
#包括
#包括
int值=0;
void*runner(void*param);
int main(){
int-pid;
pthread_t tid;
pthread_attr_t attr;
pid=fork();
如果(pid==0){
pthread_attr_init(&attr);
pthread_create(&tid,&attr,runner,NULL);
pthread_join(tid,NULL);
printf(“A:value=%d\n”,value);
}
否则,如果(pid>0){
等待(空);
printf(“B:value=%d\n”,value);
}
}
无效*流道(无效*参数){
数值=5;
pthread_退出(0);
}

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

如果您想要“ABABABAB..”则需要在线程之间进行同步,以便它们在打印单个字符后互相等待。否则,每个线程都会尽可能多地打印,同时它有CPU,任何输出组合都是可能的。注意,我们现在(因为C++ 11)而不是<代码> pthRead()。为什么在C++中使用原始P螺纹?和朋友有什么问题?@JesperJuhl@Jarod42这是我的教授希望我们键入代码的方式。我已经读到我们现在可以使用
,但他不想这样。@Shayra在我看来,你的教授落后于时代了。。。