c++ - 运行多个分离线程的意外行为
问题描述
我正在尝试创建一个执行一些计算的多线程程序。这是我正在尝试做的一个例子:
#include <list>
#include <iostream>
#include <thread>
using namespace std;
mutex mtx;
class fire {
public:
int th;
fire(int thr) {
this->th = thr;
}
void execute() {
for(int x = 0; x < 10; x++) {
mtx.lock();
cout << "thread : " << this->th << " loop : " << x << endl;
mtx.unlock();
}
}
thread exec() {
cout << "Execute\n";
return thread([=] { execute(); } );
}
};
int main(void) {
list<fire> move;
for(int x = 0; x < 8; x++) {
move.push_back(fire(x));
}
for ( auto x : move) {
thread z = x.exec();
z.detach();
}
cout << "End\n";
}
输出是:
Execute
Execute
Execute
thread : 2 loop : 0
thread : 2 loop : 1
thread : 2 loop : 2
thread : 2 loop : 3
thread : 2 loop : 4
thread : 2 loop : 5
thread : 2 loop : 6
thread : 2 loop : 7
thread : 2 loop : 8
thread : 2 loop : 9
Execute
thread : 3 loop : 0
thread : 3 loop : 1
thread : Execute
4 loop : 2
thread : 4 loop : 3
Execute
thread : 5 loop : 0
thread : 5 loop : 1
Execute
Execute
End
如您所见,这不是预期的行为,我对 Google 搜索感到筋疲力尽。为什么我没有从这段简单的代码中看到正常行为?
解决方案
你忘了pthread_exit
在结束时打电话main
。从main
终止进程返回,不给分离的线程运行时间。
但作为一般规则,最好不要分离线程。
推荐阅读
- java - 如何将 gridbaglayout 与它们所在的 JPanel 左上角的组件对齐
- excel - 当多个用户在服务器上打开 excel 文件时,控制框被重新定位
- spring-boot - 使用 Spring Restdoc 时配置 asciidoctor
- apache-nifi - easyrule-nar 文件没有向 nifi 添加任何进程
- database - Redshift Serializable Isolation 违反错误消息事务 id 错误?
- debugging - 多个用户在单个 Kubernetes 集群中调试 Pod
- docker - 在 docker env 中使用 nginx 和 node js 应用程序在 30 秒后得到 503
- javascript - jquery - 计算输入的多个数字
- python - Python 'tuple' 对象没有属性 'find'
- tomcat - 向Tomcat发送POST请求时如何解决浏览器中的Javascript fetch API错误?