溫馨提示×

C++怎樣利用_beginthreadex實(shí)現(xiàn)線程同步

c++
小樊
81
2024-10-09 19:23:15
欄目: 編程語言

在C++中,使用_beginthreadex函數(shù)創(chuàng)建一個新線程,并通過使用互斥對象(mutex)來實(shí)現(xiàn)線程同步。互斥對象可以確保多個線程不會同時訪問共享資源,從而避免數(shù)據(jù)競爭和不一致問題。

下面是一個簡單的示例,展示了如何使用_beginthreadex和互斥對象實(shí)現(xiàn)線程同步:

#include <iostream>
#include <thread>
#include <mutex>

std::mutex mtx; // 全局互斥對象
int shared_data = 0; // 共享資源

void thread_function() {
    for (int i = 0; i < 100000; ++i) {
        std::unique_lock<std::mutex> lock(mtx); // 加鎖
        ++shared_data; // 修改共享資源
        lock.unlock(); // 解鎖
    }
}

int main() {
    const int num_threads = 4;
    std::thread threads[num_threads];

    // 創(chuàng)建多個線程
    for (int i = 0; i < num_threads; ++i) {
        threads[i] = std::thread(thread_function);
    }

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

    std::cout << "Shared data: " << shared_data << std::endl; // 輸出共享資源的值

    return 0;
}

在上面的示例中,我們創(chuàng)建了一個全局互斥對象mtx和一個共享資源shared_data。然后,我們定義了一個線程函數(shù)thread_function,該函數(shù)使用互斥對象來保護(hù)對共享資源的訪問。在main函數(shù)中,我們創(chuàng)建了多個線程,并等待它們完成。最后,我們輸出共享資源的值,以驗(yàn)證所有線程都已成功修改了它。

請注意,在上面的示例中,我們在修改共享資源之前使用std::unique_lock對象對互斥對象進(jìn)行加鎖,并在修改完成后解鎖。這樣可以確保同一時間只有一個線程能夠訪問共享資源,從而實(shí)現(xiàn)線程同步。

0