为什么这个简单的线程代码会失败?
Why does this simple thread code fail?
我正试图使它做到我不能从循环调用线程。但是当我运行它时,我得到一个运行时错误:
terminate called after throwing an instance of 'std::system_error'
what(): Invalid argument Thread #1
#include <iostream>
#include <vector>
#include <memory>
#include <thread>
#include <mutex>
std::mutex m;
static int thread_count;
auto foo = [&] {
std::lock_guard<std::mutex> lock(m);
std::cout << "Thread #" << ++thread_count << std::endl;
};
int main()
{
std::vector<std::shared_ptr<std::thread>>
threads(20, std::make_shared<std::thread>(foo));
for (const auto& th : threads)
th->join();
}
您的代码实际上只创建了一个子线程,因此它在该线程上调用join()
20次。
for (int i=1; i<threads.size(); ++i)
assert(threads[i - 1].get() == threads[i].get());
你可能想用某种形式的:
创建你的向量std::vector<std::shared_ptr<std::thread>> threads(20);
for (auto & thread : threads)
thread = std::make_shared<std::thread>(foo);
相关文章:
- Netbeans 10:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
- 链接器命令失败,macOS 上的退出代码为 1(使用 -v 查看调用)
- CMake 错误:链接器命令失败,退出代码为 1 和 cpp.o 文件
- Qt:更新 QString 时自动生成的代码失败
- 使用 execv 从C++代码执行的 Linux 脚本失败
- clang:错误:链接器命令失败,退出代码为 1(使用 -v 查看调用) - 体系结构的未定义符号 x86_64:
- 如何修复 clang: 错误:链接器命令失败,退出代码为 1(使用 -v 查看调用)
- 为什么此代码导致未处理的异常失败
- 创建进程 API 失败,在窗口 122 上出现错误代码 10
- 查找在 4 和问题中代码失败的测试用例
- 多个输入的代码失败
- MSDN 站点上调用 AdjustTokenPrivileges() 的示例代码失败,并出现"Cannot enable the SE_LOCK_MEMORY_NAME privilege"
- 将C++HelloWorld国际象棋引擎代码转换为C代码失败
- 代码失败在向量的数据之前插入数字
- 编译包含动态并行性的代码失败
- 编译使用 libcxx 的套接字函数 bind() 的代码失败
- 发布版本导致简单的protobuf代码失败
- 使用opencv调试代码失败,并出现分段错误
- 有关智能指针的代码失败
- 井字游戏代码失败