铩羽而归 2020-04-15 22:15 采纳率: 0%
浏览 298

C++ 为什么要把线程装进容器中,装进容器中有什么好处:?

我在网上看到把线程装入容器;装入容器有什么好处

#include"pch.h"
#include <iostream>
#include <atomic>
#include <vector>
#include <thread>
#include <sstream>

std::atomic_flag lock = ATOMIC_FLAG_INIT;
std::stringstream stream;

void append_numer(int x)
{
    while (lock.test_and_set());
    stream << "thread#" << x << "\n";
    lock.clear();
}

int main()
{

    std::vector<std::thread> ths;
    for (int i = 0; i < 10; i++)
        ths.push_back(std::thread(append_numer, i));
    for (int i = 0; i < 10; i++)
        ths[i].join();
    std::cout << stream.str();
    return 0;
}
  • 写回答

2条回答 默认 最新

  • 小学狗喵喵叫 2020-04-16 13:42
    关注

    这里一次开了10个子线程放入容器中,方便后续遍历

    评论

报告相同问题?

悬赏问题

  • ¥15 单纯型python实现编译报错
  • ¥15 c++2013读写oracle
  • ¥15 c++ gmssl sm2验签demo
  • ¥15 关于模的完全剩余系(关键词-数学方法)
  • ¥15 有没有人懂这个博图程序怎么写,还要跟SFB连接,真的不会,求帮助
  • ¥15 PVE8.2.7无法成功使用a5000的vGPU,什么原因
  • ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
  • ¥15 安装quartus II18.1时弹出此error,怎么解决?
  • ¥15 keil官网下载psn序列号在哪
  • ¥15 想用adb命令做一个通话软件,播放录音