线程相关的问题
a thread related issue
我正在学习使用线程。我发现我可以使用以下
mutex mx;
void func(int id)
{
mx.lock();
cout << "hey , thread:"<<id << "!" << endl;
mx.unlock();
}
int main(){
vector<thread> threads;
for(int i = 0 ; i < 5 ; i++)
threads.emplace_back(thread(func , i));
for(thread & t : threads)
t.join();
return 0;
}
虽然我无法在main()
中做for(int i = 0 ; i < 5 ; i ++)
{
thread t(func , i);
threads.emplace_back(t);
}
任何人都可以解释一下吗?
您需要移动对象:
thread t(func, i);
threads.push_back(std::move(t));
emplace
也有效,但是在这种情况下,push_back
是惯用的。当然#include <utility>
。
相关文章:
- 使用 ubuntu 终端在 c++ 上运行线程类的问题
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 尝试从头开始实现Leetcode的FizzBuzz多线程问题。收到"libc++abi.dylib: terminating"错误
- 餐饮哲学家问题 - 只有 2 个线程工作
- 线程过程中的线程同步问题
- 在 C++ 的 Qt 中使用 WINAPI 线程时出现问题
- 线程和互斥锁的使用有什么问题
- 并发问题:如何只有一个线程通过关键部分
- MFC执行线程问题
- 在多线程函数中返回共享的常量指针会导致计时问题吗?
- C++多线程生产者-消费者问题
- C++ 多线程中的锁和条件变量问题
- 线程清理器检测到数据争用,问题出在哪里?
- 编译问题 C++ 同时,尝试通过调用另一个对象中的成员函数来创建 std:: 线程
- 多线程与线程小问题
- 线程池 C++ 实现问题
- 提升线程问题,当一个线程与另一个线程没有相同的副本时如何共享变量?
- 如何修复macOS线程互斥锁性能缓慢的问题?
- 多线程概念问题
- 迷宫构造函数问题 [线程 1:EXC_BAD_ACCESS(代码 = 1,地址 = 0x8)]