Created
January 6, 2015 16:34
-
-
Save yasuharu519/47149b4f5b0d4be506c3 to your computer and use it in GitHub Desktop.
マルチスレッドの使用例
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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