在 C++ 中,可以使用多个临界区来保护共享资源,以避免多个线程同时访问和修改它们。以下是一个示例代码,其中有两个临界区:

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

using namespace std;

mutex mtx1, mtx2;

void thread1() {
    for (int i = 0; i < 5; i++) {
        mtx1.lock();
        cout << 'Thread 1 is accessing resource 1' << endl;
        mtx1.unlock();

        mtx2.lock();
        cout << 'Thread 1 is accessing resource 2' << endl;
        mtx2.unlock();
    }
}

void thread2() {
    for (int i = 0; i < 5; i++) {
        mtx2.lock();
        cout << 'Thread 2 is accessing resource 2' << endl;
        mtx2.unlock();

        mtx1.lock();
        cout << 'Thread 2 is accessing resource 1' << endl;
        mtx1.unlock();
    }
}

int main() {
    thread t1(thread1);
    thread t2(thread2);

    t1.join();
    t2.join();

    return 0;
}

在上面的代码中,我们使用了两个 mutex 对象 mtx1mtx2 来保护两个共享资源。在每个线程中,我们首先锁定其中一个 mutex,然后访问相应的资源,最后解锁 mutex。然后,我们锁定另一个 mutex,访问另一个资源,最后解锁它。

这样,我们就可以确保两个线程不会同时访问同一个资源,从而避免竞态条件和数据竞争。

C++ 多个临界区:使用互斥量保护共享资源

原文地址: https://www.cveoy.top/t/topic/kWdf 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录