Home  >  Article  >  Backend Development  >  How to implement multithreading using the C++ standard library?

How to implement multithreading using the C++ standard library?

WBOY
WBOYOriginal
2024-06-03 15:06:56685browse

Methods to implement multi-threading in the C++ standard library: include header files: #include <thread> create thread objects: std::thread t(function_or_lambda) start threads: t.start() wait for threads to complete: t.join ()

How to implement multithreading using the C++ standard library?

Use the C++ standard library to implement multi-threading

Multi-threading refers to executing multiple different tasks at the same time in a program. This is for improving Program concurrency and responsiveness are very important concepts. The C++ standard library provides several classes and functions that make multithreading easy.

Here's how to implement multithreading using the C++ standard library:

  1. Include header files:

    #include <thread>
  2. Create a thread object:
    Use the std::thread class to create a thread object and specify the function or callable object to be executed.

    std::thread t(function_or_lambda);
  3. Start the thread:
    Use the std::thread::start() method to start the thread. This method will start a new thread and execute the specified function or callable object.

    t.start();
  4. Wait for a thread to complete:
    Use the std::thread::join() method to wait for a thread to complete its task.

    t.join();

Practical case:

Calculate the sum of multiple numbers:

Use multi-threading to calculate the sum of a set of numbers sum. Split the array into multiple subarrays and create multiple threads to calculate the sum of each subarray simultaneously. Finally, the sum of the subarrays calculated by each thread is added to obtain the total.

#include <thread>
#include 

using namespace std;

vector numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int num_threads = 4;

int sum(const vector& arr, int start, int end) {
  int sum = 0;
  for (int i = start; i < end; i++) {
    sum += arr[i];
  }
  return sum;
}

int main() {
  // 创建线程数组
  vector threads(num_threads);

  // 计算每个线程负责的范围
  int chunk_size = numbers.size() / num_threads;
  vector partial_sums(num_threads);

  for (int i = 0; i < num_threads; i++) {
    int start = i * chunk_size;
    int end = min((i + 1) * chunk_size, numbers.size());
    
    // 创建线程并计算部分和
    threads[i] = thread(sum, ref(numbers), start, end);
  }

  // 等待所有线程完成
  for (int i = 0; i < num_threads; i++) {
    threads[i].join();
  }

  // 计算总体和
  int total_sum = 0;
  for (int partial_sum : partial_sums) {
    total_sum += partial_sum;
  }

  cout << "Total sum: " << total_sum << endl;

  return 0;
}

The above is the detailed content of How to implement multithreading using the C++ standard library?. 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