Created
July 2, 2019 05:30
-
-
Save darcyliu/645751cfba78e93b5dee998fde4a1343 to your computer and use it in GitHub Desktop.
mutex example
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
// mutex example | |
// clang++ hello.cpp -std=c++11 -o hello | |
#include <iostream> // std::cout | |
#include <thread> // std::thread | |
#include <mutex> // std::mutex | |
std::mutex mtx; // mutex for critical section | |
void print_block (int n, char c) { | |
// critical section (exclusive access to std::cout signaled by locking mtx): | |
mtx.lock(); | |
for (int i=0; i<n; ++i) { std::cout << c; } | |
std::cout << '\n'; | |
mtx.unlock(); | |
} | |
int main () | |
{ | |
std::thread th1 (print_block,50,'*'); | |
std::thread th2 (print_block,50,'$'); | |
th1.join(); | |
th2.join(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment