首页 > 文章列表 > C++ 函数库如何创建和使用多线程?

C++ 函数库如何创建和使用多线程?

多线程 c++
409 2024-04-23

答案:在 C++ 中,可以使用 std::thread 函数库创建和使用多线程以实现并发编程。详细描述:使用 std::thread 创建新线程,并在子线程中执行指定代码。使用同步机制(如互斥锁和条件变量)来确保线程安全地访问共享数据。实战案例展示了并行数组排序,其中多个线程同时对数组子集进行排序,提高了效率。

C++ 函数库如何创建和使用多线程?

C++ 函数库:创建和使用多线程

简介

多线程是一种并发编程技术,允许在同一时间内执行多个任务。在 C++ 中,可以通过使用函数库(如 std::thread)轻松创建和使用多线程。

创建线程

要创建线程,可以使用 std::thread 类:

#include <thread>

using namespace std;

void thread_function() {
  // 要在子线程中执行的代码
}

int main() {
  thread th(thread_function); // 创建新线程
  th.join(); // 等待子线程完成
  return 0;
}

同步线程

为了确保多个线程安全地访问共享数据,可以使用同步机制,如互斥锁和条件变量:

#include <mutex>
#include <condition_variable>

using namespace std;

mutex mtx; // 互斥锁
condition_variable cv; // 条件变量

int shared_data = 0; // 共享数据

void thread_function() {
  while (true) {
    mtx.lock();
    // 对共享数据进行操作
    mtx.unlock();

    // 通知等待条件变量的线程
    cv.notify_all();
  }
}

int main() {
  thread th(thread_function); // 创建线程

  // 等待条件变量被通知
  unique_lock<mutex> lock(mtx);
  cv.wait(lock);

  // 对共享数据进行操作

  th.join(); // 等待子线程完成
  return 0;
}

实战案例:并行数组排序

我们可以使用多线程对数组进行并行排序:

#include <thread>
#include <vector>
#include <algorithm>

using namespace std;

void merge(vector<int>& arr, int l, int m, int r) {
  // 对两个子数组进行归并排序
}

void merge_sort(vector<int>& arr, int l, int r) {
  if (l < r) {
    int m = l + (r - l) / 2;
    thread th1(merge_sort, ref(arr), l, m);
    thread th2(merge_sort, ref(arr), m + 1, r);
    th1.join();
    th2.join();
    merge(arr, l, m, r);
  }
}

int main() {
  vector<int> arr = {3, 1, 4, 2, 5};
  merge_sort(arr, 0, arr.size() - 1);
  return 0;
}