首頁  >  文章  >  後端開發  >  如何在 C++ 中使用 STL 實作多執行緒程式設計?

如何在 C++ 中使用 STL 實作多執行緒程式設計?

WBOY
WBOY原創
2024-06-05 11:54:57745瀏覽

在 C++ 中使用 STL 實作多執行緒程式設計涉及:使用 std::thread 建立執行緒。使用 std::mutex 和 std::lock_guard 保護共用資源。使用 std::condition_variable 協調執行緒之間的條件。此方法支援並發任務,例如檔案複製,其中多個執行緒並行處理文件區塊。

如何在 C++ 中使用 STL 实现多线程编程?

如何在C++ 中使用STL 實作多執行緒程式設計

STL(標準範本庫)為C++ 提供了一套強大的並發原語和容器,可以輕鬆實現多執行緒程式設計。本文將示範如何使用 STL 中的關鍵元件來建立多執行緒應用程式。

使用線程

要建立線程,請使用std::thread 類別:

std::thread t1(some_function);
t1.join(); // 等待线程完成

##some_function 是要並發執行的函數。

互斥量和鎖定

互斥可用於防止多個執行緒同時存取共享資源。使用

std::mutex

std::mutex m;
{
    std::lock_guard<std::mutex> lock(m);
    // 在此处访问共享资源
} // 解除 m 的锁定

條件變數

條件變數允許執行緒等待特定條件,例如當共享資源可用時。使用

std::condition_variable

std::condition_variable cv;
std::unique_lock<std::mutex> lock(m);
cv.wait(lock); // 等待 cv 信号
cv.notify_one(); // 唤醒一个等待线程

實戰案例:多執行緒檔案複製

以下程式碼示範如何使用STL 實作多執行緒檔案複製:

#include <fstream>
#include <iostream>
#include <thread>
#include <vector>

void copy_file(const std::string& src, const std::string& dst) {
    std::ifstream infile(src);
    std::ofstream outfile(dst);
    outfile << infile.rdbuf();
}

int main() {
    std::vector<std::thread> threads;
    const int num_threads = 4;

    // 创建线程池
    for (int i = 0; i < num_threads; ++i) {
        threads.emplace_back(copy_file, "input.txt", "output" + std::to_string(i) + ".txt");
    }

    // 等待所有线程完成
    for (auto& t : threads) {
        t.join();
    }

    std::cout << "Files copied successfully!" << std::endl;
    return 0;
}

以上是如何在 C++ 中使用 STL 實作多執行緒程式設計?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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