c++ - 无法理解 std::thread 用法

标签 c++ c++11 stdthread

我正在阅读有关 c++11 多线程的文档,并遇到了 std::thread 的这个例子。

代码:

void thread_task(int n) {
  ...
}

int main(int argc, const char *argv[])
{
    std::thread threads[5];
    for (int i = 0; i < 5; i++) {
        threads[i] = std::thread(thread_task, i + 1);
    }

    return 0;
}

我不明白 threads[i] = std::thread(thread_task, i + 1);std::thread 是静态函数调用,并返回 std::thread 对象的引用吗?听起来不可思议,但似乎就是代码所说的那样。

因为我会这样写:

std::thread *threads[5];
for (int i = 0; i < 5; i++) {
    threads[i] = new std::thread(thread_task, i + 1);
}

谢谢。

最佳答案

让我们来看看到底发生了什么:

std::thread threads[5];

这将创建一个包含 5 个 std::thread 对象的数组,这些对象是默认构造的。目前它们代表“不是线程”,因为这是状态默认构造让它们留在其中。

for (int i = 0; i < 5; i++) {
    threads[i] = std::thread(thread_task, i + 1);
}

这使用了 operator= 的移动形式。因为线程不可复制,只能移动,thread& operator=(thread&& t) 被定义,而 thread& operator=(const thread& t) 不是。这会将 threads[i] 中的线程对象分配给新构造的 std::thread(thread_task, i + 1);

没有理由在这里使用指针数组。它只会增加内存泄漏的可能性。

关于c++ - 无法理解 std::thread 用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18673073/

相关文章:

C++11 智能指针策略

C++线程: shared memory not updated despite absence of race

c++ - 编译时的整数值

c++ - 使用模板输入双关语

C++测试与菜单应用

c++ - 为什么 `std::basic_ifstream<char16_t>` 在 C++11 中不起作用?

c++ - 分离线程然后让它超出范围(并使其仍在运行)是否安全?

c++ - 为什么在创建线程时会出现段错误?

c++ - 如何从clock::now()重新分配time_point?

c++ - 来自具有浮点类型的模板实例化的移位编译错误