Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //*.cxx
- #include <iostream>
- #include <mutex>
- #include <shared_mutex> // requires c++14
- #include <thread>
- #include <vector>
- namespace {
- std::mutex g_msgLock;
- std::shared_timed_mutex g_testingLock;
- }
- void info(const char * msg) {
- g_msgLock.lock();
- std::cout << msg << 'n'; // don't flush
- g_msgLock.unlock();
- }
- int main(int argc, char** argv) {
- info("Start message..");
- std::vector<std::thread> threads;
- unsigned int threadCount = 10;
- threads.reserve(threadCount);
- std::vector<std::thread> threads;
- { // Scope for locking all threads
- std::lock_guard<std::shared_timed_mutex> lockAllThreads(g_testingLock); // RAII (scoped) lock
- for (unsigned int i = 0; i < threadCount; i++) {
- // Here we start the threads using lambdas
- threads.push_back(std::thread([&, i](){
- // Here we block and wait on lockAllThreads
- std::shared_lock<std::shared_timed_mutex> threadLock(g_testingLock);
- std::string msg = std::string("THREADED_TEST_INFO_MESSAGE: ") + std::to_string(i);
- info(msg.c_str());
- }));
- }
- } // End of scope, lock is released, all threads continue now
- for(auto& thread : threads){
- thread.join();
- }
- }
- Start message..
- THREADED_TEST_INFO_MESSAGE: 9
- THREADED_TEST_INFO_MESSAGE: 5
- THREADED_TEST_INFO_MESSAGE: 3
- THREADED_TEST_INFO_MESSAGE: 1
- THREADED_TEST_INFO_MESSAGE: 4
- THREADED_TEST_INFO_MESSAGE: 0
- THREADED_TEST_INFO_MESSAGE: 8
- THREADED_TEST_INFO_MESSAGE: 7
Add Comment
Please, Sign In to add comment