Home >Backend Development >C++ >What is a thread? How do you create and manage threads in C using the <thread> library?
A thread is a lightweight process within a program that can run concurrently with other threads, sharing the same resources such as memory. Threads allow for parallel execution of tasks, which can significantly improve the performance of applications, especially those with many independent tasks.
To create and manage threads in C using the <thread></thread>
library, you follow these steps:
Creating a Thread:
To create a thread, you use the std::thread
constructor and pass it a function or a callable object that the thread will execute. Here is an example:
#include <iostream> #include <thread> void threadFunction() { std::cout << "Hello from thread!" << std::endl; } int main() { std::thread t(threadFunction); t.join(); // Wait for the thread to finish return 0; }
In this example, threadFunction
is executed in a separate thread.
Managing Threads:
join()
function is used to wait for the thread to complete its execution. As shown in the example above, t.join()
ensures that the main thread waits for the newly created thread to finish before exiting.Detaching Threads: The detach()
function allows the thread to run independently of the main program. Once detached, the thread's resources are automatically released when it finishes execution:
std::thread t(threadFunction); t.detach(); // Thread runs independently
Checking Thread Status: The joinable()
function checks whether a thread object represents an active thread of execution:
if (t.joinable()) { t.join(); }
Passing Arguments to Threads:
You can pass arguments to the thread function either by value or by reference. Here's how to do it by value and by reference:
void threadFunction(int x, std::string& str) { std::cout << "x: " << x << ", str: " << str << std::endl; str = "new value"; } int main() { int x = 10; std::string str = "original value"; std::thread t(threadFunction, x, std::ref(str)); t.join(); std::cout << "str after thread: " << str << std::endl; return 0; }
Note the use of std::ref
to pass str
by reference.
Using threads in C programming offers several significant benefits:
Ensuring thread safety when using the <thread></thread>
library in C involves several key practices:
Mutexes: Use std::mutex
to protect shared resources from concurrent access. Mutexes provide mutual exclusion, allowing only one thread at a time to access a critical section of code:
#include <mutex> std::mutex mtx; int sharedData = 0; void threadFunction() { std::lock_guard<std::mutex> lock(mtx); sharedData ; }
Here, std::lock_guard
automatically locks the mutex upon construction and unlocks it upon destruction, ensuring that sharedData
is safely incremented.
Condition Variables: Use std::condition_variable
to manage threads waiting for a specific condition to be met before proceeding:
#include <condition_variable> std::mutex mtx; std::condition_variable cv; bool ready = false; void threadFunction() { std::unique_lock<std::mutex> lock(mtx); cv.wait(lock, []{ return ready; }); // Proceed with the task } int main() { // Start thread // ... { std::lock_guard<std::mutex> lock(mtx); ready = true; } cv.notify_one(); // Notify one waiting thread // ... }
Atomic Operations: Use std::atomic
for simple shared variables to ensure atomicity without the need for mutexes:
#include <atomic> std::atomic<int> sharedData(0); void threadFunction() { sharedData ; }
std::atomic
or std::shared_ptr
when appropriate to avoid race conditions.std::lock_guard
and std::unique_lock
to ensure that resources are properly released even if exceptions occur.When working with threads in C , there are several common pitfalls to be aware of and avoid:
std::lock
to lock multiple mutexes atomically.std::current_exception
and std::rethrow_exception
to handle exceptions across threads.By being aware of these pitfalls and following best practices, you can write more robust and efficient multi-threaded C programs.
The above is the detailed content of What is a thread? How do you create and manage threads in C using the <thread> library?. For more information, please follow other related articles on the PHP Chinese website!