c++ - 如何修改代码使两个线程保持打印同一行,以便终端显示'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 交错打印。
解决方案
推荐阅读
- apache-spark - Spark 提交默认命令行选项
- r - 在 Windows 上解压缩:tar.exe:打开存档时出错:gzip 解压缩失败
- go - 标准错误:$GOPATH/go.mod 存在,但不应为 file:///Users/xxx 加载视图失败
- django - objects.all().annotate 和 objects.annotate 有什么区别?
- javascript - Google电子表格更改边框并保存节点js
- django - PLY 维护请求之间的状态(Django REST 框架)
- javascript - 函数式组件渲染一次,类组件渲染两次
- python - 有没有更好的方法在 python 中编写 if 语句?
- linux - 如何读取行并创建删除 https:// 的文件
- windows-10 - 为什么haxelib不会安装flixel库