Skip to content

Instantly share code, notes, and snippets.

@yasuharu519
Created January 6, 2015 16:34
Show Gist options
  • Save yasuharu519/47149b4f5b0d4be506c3 to your computer and use it in GitHub Desktop.
Save yasuharu519/47149b4f5b0d4be506c3 to your computer and use it in GitHub Desktop.
マルチスレッドの使用例
#include <iostream>
#include <memory>
#include <mutex>
#include <random>
#include <thread>
#include <vector>
static std::mutex mux;
std::random_device seed_gen;
std::default_random_engine engine(seed_gen());
std::uniform_int_distribution<> dist(1, 10);
static void locked_cout(const std::string& message)
{
std::lock_guard<std::mutex> lock{mux};
std::cout << message << std::endl;
}
class Worker
{
public:
Worker(int num) : num_{num}
{
}
void work()
{
auto sleep = dist(engine);
locked_cout("Worker [" + std::to_string(this->num_) + "] start .. sleep " +
std::to_string(sleep) + " seconds");
std::this_thread::sleep_for(std::chrono::seconds(sleep));
locked_cout("Worker end: " + std::to_string(this->num_));
}
private:
int num_;
};
int main()
{
std::vector<std::shared_ptr<Worker>> container;
std::vector<std::thread::thread> pool;
for (int i = 0; i < 10; i++)
{
auto ptr = std::make_shared<Worker>(i);
container.emplace_back(ptr);
pool.emplace_back(std::bind(&Worker::work, ptr));
}
for (auto& th : pool)
{
th.join();
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment