Multithreading

Multithreading is the ability of multiple parts of same code to be executed at the same time. It is different from multitasking - while multitasking appears to be parallel execution, it is not executed parallelly in reality. It's just switching between two tasks, but at a very fast speed. In multitasking, individual cores pick up individual threads to work upon.

Multithreading in C++

  1 #include<iostream>
  2 #include<thread>
  3
  4 void function1() {
  5     for (int i=1 ; i<=200 ; i++) {
  6          std::cout << "+";
  7     }
  8 }
  9
 10 void function2() {
 11     for (int i=1 ; i<=200 ; i++) {
 12          std::cout << "-";
 13     }
 14 }
 15
 16 void function3(char symbol) {
 17     for (int i=1 ; i<=200 ; i++)
 18          std::cout << symbol;
 19 }
 20
 21 int main() {
 22     std::thread worker1(function1);
 23     std::thread worker2(function2);
 24     std::thread worker3(function3, '*');
 25
 26     return 0;
 27 }

Here, we are creating three threads to execute 3 functions parallelly. Try compiling the above piece of code. You might get the below error -

To solve, the above issue give -lpthread flag with the g++ command. The code will be compiled successfully, now run ./a.out - at this point you might encounter another issue.

To solve this issue, add worker1.join(); and similar lines for the other worker threads just before the final return 0 statement. That is after line 25, and before line 26. Now, if you execute the +, - will come in a haphazard way (the output might not exact be the same for you)

This join() function basically tells the current/main thread to wait until the worker thread is done with its task, and then continue on the main thread tasks.

Multithreading Code to get weather forecast every 2 seconds

#include<iostream>
#include<thread>
#include<map>
#include<string>
#include<chrono> // for using 'ms'
using namespace std::chrono_literals; // to use 'ms'

void refreshForecast(std::map<std::string, int> forecastMap) {
  while (true) {
    for (auto& item: forecastMap) {
         item.second++;
         std::cout << item.first << " -> " << item.second << std::endl;
    }

    std::this_thread::sleep_for(2000ms);
  }
}

int main() {
    std::map<std::string, int> forecastMap = {
        {"New York", 15},
        {"Chicago", 16},
        {"Kolkata", 32},
        {"Chennai", 28},
        {"Mumbai", 30}
    };

    std::thread bgWorker(refreshForecast, forecastMap);

    bgWorker.join();

    return 0;
}

Another example of multithreading - Below code snippet keeps printing Working every 1 second until the user presses 'Enter'.

#include<iostream>
#include<thread>
#include<chrono>
using namespace std::chrono_literals;

bool s_Finished = false;

void task1() {
    while (!s_Finished) {
        std::cout << "Working...\n";
        std::this_thread::sleep_for(1000ms);
    }
}

int main() {
    std::thread worker(task1);

    // below code executes on the main thread
    // waits for the user to press Enter
    std::cin.get();
    s_Finished = true;

    worker.join();

    return 0;
}

References:

Last updated