TalentJR

🧩 C++ programming tutorial for beginners · Class 11 · Lesson 17 of 18 · Free

Intro to Multithreading in C++ – std::thread, join and mutex

⏱ About 35 minutes · ▶ run real C++ here — nothing to install · no sign-in

In this lesson you will

  • Split a big job into independent chunks and combine the results
  • Start threads with std::thread and wait for them with join()
  • Explain race conditions and protect shared data with a mutex

Marking 400 answer sheets alone takes a whole day. Four teachers, each with 100 sheets, finish much sooner, as long as they add up the totals carefully at the end. Threads let one C++ program do several jobs at the same time, the same way.

What is multithreading and why split work into chunks?

A thread is one path of work inside a program. Every program has at least one: the main thread that runs main(). Multithreading means running several threads at the same time, often on different CPU cores.

Before using threads, you must split the job into pieces that do not depend on each other. Here a worker function adds up the marks for one section of the school.

This program calls the worker for each chunk one after another, on one thread. Each call could become its own thread, because the chunks never touch each other's data. This box runs in your browser; try changing the marks.

🧩 C++ — you can edit this code
Output
Chunk 0 sum: 152
Chunk 1 sum: 136
Chunk 2 sum: 144
Chunk 3 sum: 147
Total: 579

How do you create a thread in C++ with std::thread?

std::thread (header <thread>) starts a new thread. You give it a function to run. The thread starts at once, while main carries on.

join() makes main WAIT until that thread has finished. Every thread must be joined (or detached) before its std::thread object is destroyed, or the program stops.

Here main prints only before starting the thread and after join(), so the output order is always the same. On Linux g++ needs the -pthread option for threads.

📄 Example to read — threads do not run in this browser compiler — output from g++ on our computer
#include <iostream>
#include <thread>
using namespace std;

void markSheets() {
    cout << "Helper: marking 100 sheets\n";
}

int main() {
    cout << "Main: starting a helper\n";
    thread helper(markSheets);     // starts running now
    helper.join();                 // wait for it to finish
    cout << "Main: helper is done\n";
    return 0;
}
Output
Main: starting a helper
Helper: marking 100 sheets
Main: helper is done

How do you pass arguments to a C++ thread and get results back?

Extra arguments after the function name are passed to it: thread t(worker, a, b). They are COPIED into the thread.

To let a thread write into your variable, wrap it in std::ref (header <functional>). Here each thread gets its own slot in the results vector, so no two threads write to the same place.

We join every thread first and only then print. Printing from many threads at once could mix the lines up.

📄 Example to read — threads do not run in this browser compiler — output from g++ on our computer
#include <iostream>
#include <thread>
#include <vector>
#include <functional>
using namespace std;

void sumRange(const vector<int>& marks, size_t start, size_t end, int& result) {
    result = 0;
    for (size_t i = start; i < end; i++) result += marks[i];
}

int main() {
    vector<int> marks = {70, 82, 91, 45, 66, 78, 88, 59};
    vector<int> results(4);
    vector<thread> team;
    for (size_t c = 0; c < 4; c++) {
        team.emplace_back(sumRange, cref(marks), c * 2, c * 2 + 2, ref(results[c]));
    }
    for (thread& t : team) t.join();          // wait for all four

    int total = 0;
    for (size_t c = 0; c < 4; c++) {
        cout << "Thread " << c << ": " << results[c] << "\n";
        total += results[c];
    }
    cout << "Total: " << total << "\n";
    return 0;
}
Output
Thread 0: 152
Thread 1: 136
Thread 2: 144
Thread 3: 147
Total: 579

What is a race condition and how does a mutex fix it in C++?

A race condition happens when two threads change the same variable at the same time. count++ is really three steps: read, add, write. Two threads can both read 5 and both write 6, so one update is lost. The result changes from run to run, which makes these bugs very hard to find.

A mutex (mutual exclusion, header <mutex>) is a lock. Only one thread can hold it at a time; the others wait. lock_guard locks it when created and unlocks it automatically at the end of the block.

With the lock, four threads adding 100000 each always give exactly 400000. Locks make threads wait, so keep the locked part small.

📄 Example to read — threads do not run in this browser compiler — output from g++ on our computer
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
using namespace std;

int ticketsSold = 0;
mutex counterLock;

void sell(int count) {
    for (int i = 0; i < count; i++) {
        lock_guard<mutex> guard(counterLock);   // one thread at a time
        ticketsSold++;
    }                                           // unlocked here
}

int main() {
    vector<thread> counters;
    for (int i = 0; i < 4; i++) {
        counters.emplace_back(sell, 100000);
    }
    for (thread& t : counters) t.join();
    cout << "Tickets sold: " << ticketsSold << "\n";
    return 0;
}
Output
Tickets sold: 400000

How do you plan multithreaded C++ code? (runs in the browser)

Good threaded code is mostly good planning: split the data, give each worker its own output slot, then combine after everyone is done. If threads never share a variable, you need no mutex at all.

This version finds the topper in each section with a worker function and then picks the overall topper. It runs on one thread here, but each worker call could be a std::thread, exactly as in the earlier example.

Problems to know by name: a deadlock is when two threads each wait for a lock the other holds, so both wait forever. Threads also add overhead, so tiny jobs can get SLOWER with threads.

🧩 C++ — you can edit this code
Output
Section 1: Aman
Section 2: Sara
Section 3: Meera
School topper: Sara (95)

🤔 Predict the output

Think like C++: read the code and choose what it prints. You get the reason straight away.

Question 1. What does this print?

#include <iostream>
#include <thread>
using namespace std;

void work() { cout << "work "; }

int main() {
    cout << "start ";
    thread t(work);
    t.join();
    cout << "end\n";
    return 0;
}

Question 2. What does this print?

#include <iostream>
#include <thread>
#include <mutex>
using namespace std;

int total = 0;
mutex m;

void add(int n) {
    for (int i = 0; i < n; i++) {
        lock_guard<mutex> g(m);
        total++;
    }
}

int main() {
    thread a(add, 1000);
    thread b(add, 1000);
    a.join();
    b.join();
    cout << total << "\n";
    return 0;
}

Question 3. What does this print?

#include <iostream>
#include <thread>
#include <functional>
using namespace std;

void addFive(int& x) { x += 5; }

int main() {
    int n = 10;
    thread t(addFive, ref(n));
    t.join();
    cout << n << "\n";
    return 0;
}

🧩 Your challenge

Plan a multithreaded fee report (this runs in the browser, so call the worker one chunk at a time). Four sections paid these fees. Write sectionTotal, which adds up one section's fees and also counts how many students paid more than Rs 1500. Store each section's result in its own slot of a vector, then combine. Expected output: Section 1: Rs 6000, 1 above 1500 Section 2: Rs 7000, 2 above 1500 Section 3: Rs 4500, 0 above 1500 Section 4: Rs 8000, 2 above 1500 School: Rs 25500, 5 above 1500

Expected output :
Section 1: Rs 6000, 1 above 1500
Section 2: Rs 7000, 2 above 1500
Section 3: Rs 4500, 0 above 1500
Section 4: Rs 8000, 2 above 1500
School: Rs 25500, 5 above 1500
🧩 C++ — you can edit this code

⚠️ Common mistakes (and how to fix them)

❌ Wrong

#include <iostream>
#include <thread>
using namespace std;

void work() { cout << "Marking sheets\n"; }

int main() {
    thread t(work);
    cout << "Main is done\n";
    return 0;
}

terminate called without an active exception

✅ Right

#include <iostream>
#include <thread>
using namespace std;

void work() { cout << "Marking sheets\n"; }

int main() {
    thread t(work);
    t.join();
    cout << "Main is done\n";
    return 0;
}

A std::thread that is still joinable when it is destroyed calls std::terminate and stops the program. Always join() (or detach()) every thread.

❌ Wrong

#include <iostream>
#include <thread>
using namespace std;

void work() { cout << "Marking sheets\n"; }

int main() {
    thread t(work());
    t.join();
    return 0;
}

Line 8: error: invalid use of void expression

✅ Right

#include <iostream>
#include <thread>
using namespace std;

void work() { cout << "Marking sheets\n"; }

int main() {
    thread t(work);
    t.join();
    return 0;
}

work() CALLS the function right now, on the main thread, and passes its result (nothing, void) to thread. Pass the function itself, without brackets: thread t(work).

❌ Wrong

#include <iostream>
#include <thread>
using namespace std;

void work() { cout << "Working\n"; }

int main() {
    thread t(work);
    t.join();
    t.join();
    cout << "Done\n";
    return 0;
}

terminate called after throwing an instance of 'std::system_error'

✅ Right

#include <iostream>
#include <thread>
using namespace std;

void work() { cout << "Working\n"; }

int main() {
    thread t(work);
    if (t.joinable()) t.join();
    if (t.joinable()) t.join();    // skipped: already joined
    cout << "Done\n";
    return 0;
}

A thread can be joined only once. The second join() throws an error that stops the program. Check joinable() first.

📌 Remember

  • A thread is one path of work; std::thread starts a new one.
  • join() waits for a thread; every thread must be joined or detached.
  • Arguments are copied into the thread; use std::ref to share a variable.
  • A race condition is two threads changing the same data at once; results become random.
  • A mutex with lock_guard lets one thread at a time into the shared part.
  • Best plan: split the data, give each worker its own slot, combine after join.

Finished the quiz and the challenge?

Questions students ask

What is the difference between a process and a thread?

A process is a running program with its own memory. Threads live inside one process and share its memory. That sharing makes threads fast to talk to each other, but also causes race conditions.

Does more threads always mean faster?

No. A computer has a limited number of cores, and starting threads costs time. Small jobs, or jobs where threads keep waiting for a lock, can become slower.

Why don't threads run in the browser here?

This browser compiler runs your program in WebAssembly on a single thread, so <thread> is not available. The read-only boxes show output from g++ on a normal computer. The planning examples run in your browser.

What is a deadlock?

A deadlock is when thread A holds lock 1 and waits for lock 2, while thread B holds lock 2 and waits for lock 1. Both wait forever. Locking in the same order everywhere, or using std::scoped_lock, avoids it.