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.
Section overview
5 resourcesExplores 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:
- Create two threads and make each of them print a different message.
- 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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Random Password Generator
Create secure, complex passwords with custom length and character options.
Use toolLatest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article