Skip to content

Instantly share code, notes, and snippets.

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

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).
std::cout << i << std::endl;
// Sleep for one second before attempting to print the next number
// to make the effect of threading more visible.
int main() {
std::cout << "Starting to count..." << std::endl;
std::thread a(do_count, 3);
std::thread b(do_count, 6);
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.