Threading Library

Basics

  • What is multithreading?
  • Why multithreading?

Overview of C+ thread library

Let us start with an easy example:

#include <iostream>
#include <thread>

void helloFunction() {
    std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 1000));
    std::cout << "Hello from a thread!\n";
}

int main() {
    std::thread t1(helloFunction);
    std::thread t2(helloFunction);
 
    std::cout << "We have launched two threads to operate in parallel!" << std::endl;

    t1.join();  // Wait for the thread to finish
    t2.join();
 
    return 0;
}
Back to top