环境: VS2017
#include <iostream>
#include <thread>
#include <mutex>
#include <memory>
#include <vector>
#include <algorithm>
constexpr auto newl = '\n';
const std::unique_ptr<std::mutex> cout_mutex_ptr = std::make_unique<std::mutex>();
std::vector<std::thread> create_threads(int numThreads);
std::thread create_thread(int threadNum);
int main()
{
try
{
auto threads = create_threads(3);
std::for_each(threads.rbegin(), threads.rend(),
[](std::thread& t) -> void {t.join(); });
auto lock = std::lock_guard{ *cout_mutex_ptr };
std::cout << "All threads said hello, so goodbye." << newl;
return 0;
}
catch(...)
{
return -1;
}
}
std::vector<std::thread> create_threads(int numThreads)
{
if (numThreads < 1) throw std::invalid_argument{ "Argument must be positive." };
size_t num = static_cast<size_t>(numThreads);
auto ret = std::vector<std::thread>{};
int thisThread = 0;
while (ret.size() < num)
{
ret.emplace_back(create_thread(++thisThread));
}
return ret;
}
std::thread create_thread(int threadNum)
{
auto doMe = [=]() -> void
{
auto lockguard = std::lock_guard{ *cout_mutex_ptr };
std::cout << "Hello world, from thread number: " << threadNum << "." << newl;
};
return std::thread{ doMe };
}