借助vector存放多个线程thread对象,借助vector和它的迭代器实现创建和运行多个线程,代码如下:
-
- #include
- #include
- #include
- using namespace std;
-
- void myprint(int inum)
- {
- cout << "myprint线程开始执行了,线程编号 = " << inum << endl;
- cout << "myprint线程结束执行了,线程编号 = " << inum << endl;
- return;
- }
-
- int main()
- {
- vector
mythreads; - // 创建10个线程,线程入口函数统一使用 myprint
- for (int i = 0; i < 10; i++)
- {
- // 创建线程,并开始执行
- mythreads.push_back(thread(myprint, i));
- }
- for (auto iter = mythreads.begin(); iter != mythreads.end(); ++iter)
- {
- iter->join();// 等待线程返回
- }
-
- cout << "main over" << endl;
- return 0;
- }