Skip to content

Instantly share code, notes, and snippets.

@fleroviux fleroviux/threads.cpp
Last active Sep 28, 2018

Embed
What would you like to do?
Minimal C++11 threading example for LF6 @MMBbS
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
static std::mutex g_cout_mutex; /* Mutex means "mutually exclusive" */
/**
* Count from zero to maximum number in a thread-safe manner.
*
* @param int max Maximum value
* @returns nothing
*/
void do_count(int max) {
for (int i = 0; i <= max; i++) {
// While 'std::cout' itself is thread-safe, we are writing to it twice actually
// (the number and newline) which is not atomic anymore. To prevent interleaved text
// we define a critical section using a lock (mutex).
g_cout_mutex.lock();
std::cout << i << std::endl;
g_cout_mutex.unlock();
// Sleep for one second before attempting to print the next number
// to make the effect of threading more visible.
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main() {
std::cout << "Starting to count..." << std::endl;
std::thread a(do_count, 3);
std::thread b(do_count, 6);
a.join();
b.join();
std::cout << "Finished!" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.