首頁  >  文章  >  後端開發  >  C++ 函式庫如何建立和使用多執行緒?

C++ 函式庫如何建立和使用多執行緒?

WBOY
WBOY原創
2024-04-18 14:39:02947瀏覽

答案:在 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;
}

以上是C++ 函式庫如何建立和使用多執行緒?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn