温馨提示×

如何在c++中使用synchronized关键字

c++
小樊
83
2024-08-13 19:12:42
栏目: 编程语言

在C++中,没有内置的synchronized关键字,但是可以通过使用std::mutexstd::lock_guard来实现同步操作。

下面是一个使用std::mutex实现同步的示例代码:

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

std::mutex mtx;

void synchronizedFunction() {
    mtx.lock();
    // 在这里执行需要同步的操作
    std::cout << "执行同步操作" << std::endl;
    mtx.unlock();
}

int main() {
    std::thread t1(synchronizedFunction);
    std::thread t2(synchronizedFunction);

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

    return 0;
}

在上面的示例中,std::mutex用于实现同步,mtx.lock()mtx.unlock()分别用于锁定和释放互斥量。

另外,std::lock_guard也可以用于自动管理互斥量的锁定和解锁。下面是一个使用std::lock_guard实现同步的示例代码:

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

std::mutex mtx;

void synchronizedFunction() {
    std::lock_guard<std::mutex> lock(mtx);
    // 在这里执行需要同步的操作
    std::cout << "执行同步操作" << std::endl;
}

int main() {
    std::thread t1(synchronizedFunction);
    std::thread t2(synchronizedFunction);

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

    return 0;
}

在上面的示例中,std::lock_guard用于管理互斥量的锁定和解锁,创建lock_guard对象时会自动锁定互斥量,当lock_guard对象超出作用域时会自动解锁互斥量。

0