Home >Backend Development >C++ >Best practices for multi-threaded programming in C++

Best practices for multi-threaded programming in C++

WBOY
WBOYOriginal
2024-05-31 21:33:01357browse

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.

C++ 多线程编程的最佳实践

C Best practices for multi-threaded programming

Understanding the concept of multi-threading

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.

Creating and managing threads

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

Synchronization and communication are crucial when multiple threads access shared resources. C provides a variety of synchronization primitives, including:

  • Mutex (Mutex): Allows only one thread to access the critical section at a time.
  • Condition Variable: Allows a thread to wait for a certain condition to be met.
  • Atomic Operation: Provides thread-safe update and read operations.

Practical Case: Parallel Computing

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn