线程相关的问题

a thread related issue

本文关键字:问题 线程      更新时间:2023-10-16

我正在学习使用线程。我发现我可以使用以下

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>