如何创建线程对象的C ++ 11的阵列? [英] How to create an array of thread objects in C++11?

查看:119
本文介绍了如何创建线程对象的C ++ 11的阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要学习如何与新的C ++标准库创建多个线程和存储的句柄到一个数组。结果
我如何启动一个线程?结果
我看到先从构造一个线程,但如果我使用数组,我不能调用构造函数的例子。

 的#include<&iostream的GT;
#包括LT&;螺纹>无效EXEC(INT N){
    性病::法院LT&;< 线程<< N'LT;<的std :: ENDL;
}INT主(INT ARGC,CHAR *的argv []){    的std ::线程myThreads [4];    对(INT I = 0; I&下; 4;我++){
        //myThreads[i].start(exec,I); //?创建,启动运行
        //新(安培; myThreads [I])的std ::线程(EXEC,I); //我试了一下,似乎工作,但它看起来像一个不好的设计或反模式。
    }
    对(INT I = 0; I&下; 4;我++){
        myThreads [I]。加入();
    }}


要求

解决方案

没什么特别的;只需使用分配。你的内部循环,写

  myThreads [I] =的std ::线程(EXEC,I);

和它应该工作。

I want to learn how to create multiple threads with the new C++ standard library and store their handles into an array.
How can I start a thread?
The examples that I saw start a thread with the constructor, but if I use array, I cannot call the constructor.

#include <iostream>
#include <thread>

void exec(int n){
    std::cout << "thread " << n << std::endl;
}

int main(int argc, char* argv[]){

    std::thread myThreads[4];

    for (int i=0; i<4; i++){
        //myThreads[i].start(exec, i); //?? create, start, run
        //new (&myThreads[i]) std::thread(exec, i); //I tried it and it seems to work, but it looks like a bad design or an anti-pattern.
    }
    for (int i=0; i<4; i++){
        myThreads[i].join();
    }

}

解决方案

Nothing fancy required; just use assignment. Inside your loop, write

myThreads[i] = std::thread(exec, i);

and it should work.

这篇关于如何创建线程对象的C ++ 11的阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆