std::mutex

std::mutex 和其变体是 C++ 中用于线程同步的重要工具。让我们详细了解一下这四种互斥量的作用和使用案例:

  1. std::mutex
  1. std::mutex 是一种独占式互斥量,用于保护共享数据,确保在同一时间只有一个线程可以访问它。
  2. 它不支持递归锁定,即同一线程不能多次锁定同一个 std::mutex
  3. 不带超时功能。
  1. std::recursive_mutex
  • std::recursive_mutex 是递归互斥量,允许同一线程多次锁定它,避免死锁。
  • 可重入性使得在递归函数中使用更方便。
  • 不带超时功能。
  1. std::timed_mutex

    • std::timed_mutex 具有超时功能,可以在一段时间内尝试获取锁。
    • 不能递归使用,只能在不需要递归锁定的场景中使用。
  2. std::recursive_timed_mutex

    • std::recursive_timed_mutex 是带超时功能的递归互斥量。
    • 允许同一线程多次锁定,并且支持超时。
    • 可以在需要递归锁定且具有超时需求的场景中使用。

下面是一个示例,展示如何使用这些互斥量:

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

std::mutex mtx; // std::mutex 示例

void worker() {
    mtx.lock();
    std::cout << "Thread " << std::this_thread::get_id() << " acquired the mutex." << std::endl;
    mtx.unlock();
}

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

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

    return 0;
}

std::timed_mutex 是一种带有超时功能的互斥量,用于多线程编程。让我们看看如何使用它:

  1. 等待一段时间获取锁

    • std::timed_mutex 允许你等待一段时间来获取锁。如果在规定的等待时间内成功获取锁,或者超时了未获取到锁,就继续执行。
    • 使用 try_lock_for() 成员函数来实现这一功能。
  2. 示例代码: 下面是一个使用 std::timed_mutex 的示例,其中我们创建了一个计数器并在多个线程中增加它:

#include <algorithm>
#include <chrono>
#include <iostream>
#include <vector>
#include <thread>
#include <mutex>
using namespace std;
using namespace std::chrono;


volatile int counter(0); // Non-atomic counter
std::timed_mutex myMutex;

void increases10k() {
    for (int i = 0; i < 10000; ++i) {
        if (myMutex.try_lock_for(std::chrono::milliseconds(100))) {
            ++counter;
            myMutex.unlock();
        }
        // You can add other processing logic here
    }
}

int main() {
    std::thread threads[10];
    auto start = high_resolution_clock::now();
    for (int i = 0; i < 10; ++i) {
        threads[i] = std::thread(increases10k);
    }

    for (auto& th : threads) {
        th.join();
    }

    std::cout << "Successfully incremented counter value: " << counter << std::endl;
    auto stop = high_resolution_clock::now();
    auto duration = duration_cast<microseconds>(stop - start);
    cout << "函数执行时间:" << duration.count() << " 微秒" << endl;
    return 0;
}

运行结果:

在上面的示例中,我们使用 try_lock_for() 来尝试获取锁。如果在规定的等待时间内成功获取锁,就会增加计数器的值。否则,线程会继续执行而不会被阻塞。

  • 7
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

aFakeProgramer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值