Home >Backend Development >C++ >Best practices for multi-threaded programming in C++
Multi-threaded programming understands the concept of multi-threading, uses the std::thread library to create and manage threads, and achieves synchronization and communication through mutexes, condition variables and atomic operations. Practical case: Use multi-threads for parallel computing, allocate tasks to multiple threads, and accumulate results to improve efficiency.
Multi-threaded programming is a concurrent programming paradigm that Allows multiple tasks to be performed at the same time. In C, multithreading can be easily implemented using the std::thread
library.
To create a thread, you can use the std::thread
constructor and pass a callable object as a parameter:
#include <thread> void print_hello() { std::cout << "Hello from a thread!" << std::endl; } int main() { std::thread t(print_hello); t.join(); // 等待线程完成执行 return 0; }
Synchronization and communication are crucial when multiple threads access shared resources. C provides a variety of synchronization primitives, including:
The following is a practical case using multi-threads for parallel computing:
#include <thread> #include <vector> std::vector<int> numbers; // 输入数组 void calculate_sum(int start, int end, int& sum) { for (int i = start; i < end; i++) { sum += numbers[i]; } } int main() { // 将输入数组分成多个部分 std::vector<int> parts; int part_size = numbers.size() / 4; for (int i = 0; i < 4; i++) { parts.push_back(i * part_size); } parts.push_back(numbers.size()); // 创建线程并分配每个部分的任务 std::vector<std::thread> threads; std::vector<int> sums(4); for (int i = 0; i < 4; i++) { threads.push_back(std::thread(calculate_sum, parts[i], parts[i + 1], std::ref(sums[i]))); } // 等待所有线程完成并累加结果 for (auto& t : threads) { t.join(); } int total_sum = accumulate(sums.begin(), sums.end(), 0); std::cout << "Total sum: " << total_sum << std::endl; return 0; }
By parallel computing on multiple threads, the The program can significantly improve computational efficiency.
The above is the detailed content of Best practices for multi-threaded programming in C++. For more information, please follow other related articles on the PHP Chinese website!