Last active
November 5, 2020 20:39
-
-
Save cesarvr/a40c208c7caefa424a5029158ad679f5 to your computer and use it in GitHub Desktop.
Just a quick example to demonstrate information passing between two thread without a mutex.
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 <chrono> | |
#include <iostream> | |
#include <queue> | |
#include <thread> | |
/* | |
* This program demonstrate that using one thread to write and another to read is ok to get ordered values from a queue. | |
* | |
* One thread generate a ordered sequence of number, another consumes print the sequence | |
* the queue do its job to make sure the sequence order is correct. | |
* | |
* To run this: | |
* g++ main.cpp -o test -std=c++17 && ./test | |
* | |
* Running this will generate this: | |
* getting: pushing stuff 0 queue size: 20 | |
* getting: pushing stuff 0 queue size: 30 | |
* getting: pushing stuff 1 queue size: 40 | |
* getting: pushing stuff 0 queue size: 51 | |
* | |
*/ | |
std::queue<std::string> my_queue; | |
void push_stuff_in(int num) { | |
for (int i = 0; i < num; i++) { | |
std::string m = "pushing stuff " + std::to_string(i); | |
my_queue.push(m); | |
std::this_thread::sleep_for(std::chrono::milliseconds(50)); | |
} | |
} | |
void get_stuff_out() { | |
while (!my_queue.empty()) { | |
auto entry = my_queue.front(); | |
std::cout << "getting: " << entry << " queue size: " << my_queue.size() | |
<< std::endl; | |
std::this_thread::sleep_for(std::chrono::milliseconds(600)); | |
my_queue.pop(); | |
} | |
} | |
int main() { | |
std::thread t1{[]() { | |
int cnt = 0; | |
while (true) { | |
cnt++; | |
push_stuff_in(cnt); | |
} | |
}}; | |
std::thread t2{[]() { | |
while (true) { | |
get_stuff_out(); | |
std::this_thread::sleep_for(std::chrono::seconds(1)); | |
} | |
}}; | |
t2.join(); | |
t1.join(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment