C++ / C++ Multithreading and Concurrency

Working with Threads in C++

This tutorial will guide you through the process of creating and managing threads in C++. You will learn how to start, stop, and control threads using the C++ standard library.

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores multithreading concepts to enable concurrent execution in C++.

1. Introduction

This tutorial will take you through the process of creating and managing threads in C++. Threads are a way for a program to divide itself into two or more concurrently running tasks. They allow programs to do more than one thing at a time.

By the end of this tutorial, you will learn how to:
- Create threads in C++
- Stop and control threads
- Avoid common pitfalls

Prerequisites: Familiarity with C++ syntax and basic knowledge of how functions work in C++.

2. Step-by-Step Guide

C++ Standard Library provides support for threading via <thread>, <mutex>, <condition_variable> and other related headers. A thread is created by constructing a std::thread object and providing the function you want the system to run as a separate thread.

Creating Threads

To create a thread, you need to construct a std::thread object and pass it a function:

#include <thread>

void my_function() {
    // code to be executed by the thread
}

int main() {
    std::thread my_thread(my_function); // create a thread that runs my_function
    my_thread.join(); // wait for my_thread to finish
    return 0;
}

Stopping Threads

Threads are stopped when they finish executing their code, but they can also be stopped prematurely using std::thread::detach.

Controlling Threads

You can control threads in several ways. The most common way is to use std::this_thread::sleep_for to make a thread sleep for a certain period of time.

3. Code Examples

Here are some practical examples of working with threads in C++.

Example 1: Creating a thread

#include <iostream>
#include <thread>

// This function will be executed by the thread
void thread_function() {
    std::cout << "Hello from thread!\n";
}

int main() {
    // Create a thread that runs thread_function
    std::thread my_thread(thread_function);

    // Wait for my_thread to finish
    my_thread.join();

    std::cout << "Hello from main!\n";

    return 0;
}

Expected output:

Hello from thread!
Hello from main!

Example 2: Making a thread sleep

#include <iostream>
#include <thread>
#include <chrono>

void thread_function() {
    std::this_thread::sleep_for(std::chrono::seconds(3)); // make the thread sleep for 3 seconds
    std::cout << "Hello from thread after 3 seconds!\n";
}

int main() {
    std::thread my_thread(thread_function);
    my_thread.join();
    std::cout << "Hello from main!\n";
    return 0;
}

Expected output (after 3 seconds):

Hello from thread after 3 seconds!
Hello from main!

4. Summary

In this tutorial, we have covered:
- How to create threads in C++
- How to stop and control threads

As a next step, you can learn about more advanced threading concepts, such as mutexes and condition variables. The C++ documentation is a great resource for that.

5. Practice Exercises

Here are some exercises for you to practice:

  1. Create two threads and make each of them print a different message.
  2. Create a thread that sleeps for 5 seconds before printing a message, and make the main function print a message immediately.

Solutions:

#include <iostream>
#include <thread>

void thread_function1() {
    std::cout << "Hello from thread 1!\n";
}

void thread_function2() {
    std::cout << "Hello from thread 2!\n";
}

int main() {
    std::thread my_thread1(thread_function1);
    std::thread my_thread2(thread_function2);
    my_thread1.join();
    my_thread2.join();
    return 0;
}

2.

#include <iostream>
#include <thread>
#include <chrono>

void thread_function() {
    std::this_thread::sleep_for(std::chrono::seconds(5)); // make the thread sleep for 5 seconds
    std::cout << "Hello from thread after 5 seconds!\n";
}

int main() {
    std::thread my_thread(thread_function);
    std::cout << "Hello from main!\n";
    my_thread.join();
    return 0;
}

Remember, practice is key. Keep experimenting with these concepts to gain a deeper understanding of threads in C++.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Robots.txt Generator

Create robots.txt for better SEO management.

Use tool

QR Code Generator

Generate QR codes for URLs, text, or contact info.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Timestamp Converter

Convert timestamps to human-readable dates.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help