Threads in C Threads are lightweight execution units that enable concurrent programming. Use the std::thread class to create threads and maintain the consistency of shared data through synchronization mechanisms such as mutex locks, condition variables, and spin locks. The practical case shows the process of using threads to calculate the sum concurrently.
Threads are lightweight execution units that share the same address space with processes and can implement concurrent programming.
In C, use the std::thread
class to create a thread:
#include <thread> void thread_function() { // 执行线程任务 } int main() { std::thread thread(thread_function); thread.join(); // 阻塞主线程,直到线程执行完毕 return 0; }
is To maintain the consistency of shared data between threads, you need to use a synchronization mechanism:
#include <mutex> std::mutex mutex; void thread_function() { std::lock_guard<std::mutex> lock(mutex); // 对共享数据进行操作 }
#include <condition_variable> std::condition_variable cv; std::mutex cv_mutex; void thread_function() { std::unique_lock<std::mutex> lock(cv_mutex); cv.wait(lock, [] { return condition_is_met; }); // 条件满足时,继续执行 }
#include <atomic> std::atomic_flag spinlock = ATOMIC_FLAG_INIT; void thread_function() { while (spinlock.test_and_set(std::memory_order_acquire)); // 对共享数据进行操作 spinlock.clear(std::memory_order_release); }
Concurrent calculation and summation
#include <thread> #include <vector> std::mutex sum_mutex; long long sum = 0; void add_numbers(const std::vector<int>& numbers) { for (int num : numbers) { std::lock_guard<std::mutex> lock(sum_mutex); sum += num; } } int main() { std::vector<std::thread> threads; std::vector<int> numbers = {...}; // 要相加的数字列表 // 创建并执行线程 for (size_t i = 0; i < std::thread::hardware_concurrency(); i++) { threads.emplace_back(add_numbers, numbers); } // 等待所有线程结束 for (auto& thread : threads) { thread.join(); } std::cout << "Sum: " << sum << std::endl; return 0; }
The above is the detailed content of How to create and manage threads in C++? What thread synchronization mechanisms are there?. For more information, please follow other related articles on the PHP Chinese website!