C++ —— 线程同步(互斥锁)

C++ ------ 线程同步(互斥锁)

线程同步

线程同步:多线程协同工作,协商如何使用共享资源。
C++11线程同步包含三部分内容:

  1. 互斥锁(互斥量)
  2. 条件变量
  3. 生产/消费者模型

互斥锁(互斥量)

只有加锁解锁两种状态,确保同一时间只有一个线程访问共享资源。

访问共享资源之前加锁,加锁成功访问资源,访问完成解锁释放。

若某线程持有锁,其他线程形成等待队列

C++11提供了4种互斥锁:

  • mutex:互斥锁(最常用)
  • timed_mutex:带超时机制的互斥锁
  • recursive_mutex:递归互斥锁
  • recursive_timed_mutex:带超时机制的递归互斥锁

测试代码

cpp 复制代码
#include <iostream>
#include <thread>
using namespace std;

void func (int n, const string& s) {
    for (int i = 1; i <= 10; i++) {
        cout << "No." << i << ", n = " << n << ", s = " << s << endl;
        this_thread::sleep_for(chrono::seconds(1));
    }
}
a
int main () {
    thread t1(func, 1, "t1");
    thread t2(func, 2, "t2");
    thread t3(func, 3, "t3");
    thread t4(func, 4, "t4");
    thread t5(func, 5, "t5");
    thread t6(func, 6, "t6");

    t1.join();
    t2.join();
    t3.join();
    t4.join();
    t5.join();
    t6.join();

    return 0;
}

cout属于全局对象,若多线程都用它向屏幕输出文字,会出乱子。线程越多,越容易乱。

mutex互斥锁

使用互斥锁cout加锁,代码如下:

cpp 复制代码
#include <iostream>
#include <thread>
#include <mutex> // 使用互斥锁需要包含的头文件
using namespace std;

mutex mtx; // 创建互斥锁对象,用于保护共享资源cout对象。

void func (int n, const string& s) {
    for (int i = 1; i <= 10; i++) {
        // 每次调用cout对象之前,申请加锁
        mtx.lock();
        cout << "No." << i << ", n = " << n << ", s = " << s << endl;
        // 用完了就解锁
        mtx.unlock();
        this_thread::sleep_for(chrono::seconds(1));
    }
}

int main () {
   // 代码不变...
}

再看一段示例代码:

cpp 复制代码
#include <iostream>
#include <chrono> // 时间相关操作的头文件
#include <thread> // 线程相关操作的头文件
#include <mutex> // 互斥锁的头文件
using namespace std;

int a = 0;
mutex mtx; // 创建互斥锁对象,用于保护共享资源a变量。

void func () {
    for (int i = 0; i < 1000000; ++i) {
        mtx.lock();
        a++;
        mtx.unlock();
    }
}

int main () {
    auto start = chrono::steady_clock::now();
    thread t1(func);
    thread t2(func);

    t1.join();
    t2.join();
    auto end = chrono::steady_clock::now();
    cout << "time = " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << "ms" << endl;
    cout << "a = " << a << endl;

    return 0;
}

运行结果:

time = 101ms

a = 2000000

在代码中添加一些打印信息,能更清楚的观察到:两个线程申请加锁,只有一个成功,另外一个线程等待,直到第一个线程解锁后第二个线程才能加锁。

cpp 复制代码
#include <iostream>
#include <chrono> // 时间相关操作的头文件
#include <thread> // 线程相关操作的头文件
#include <mutex> // 互斥锁的头文件
using namespace std;

int a = 0;
mutex mtx;

void func () {
    for (int i = 0; i < 1000000; ++i) {
        cout << "thread id: " << this_thread::get_id() << ", 申请加锁" << endl;
        mtx.lock();
        cout << "thread id: " << this_thread::get_id() << ", 加锁成功" << endl;
        a++;
        this_thread::sleep_for(chrono::seconds(5));
        mtx.unlock();
        cout << "thread id: " << this_thread::get_id() << ", 解锁" << endl;
        this_thread::sleep_for(chrono::seconds(1));
    }
}

int main () {
    thread t1(func);
    thread t2(func);

    t1.join();
    t2.join();
    
    cout << "a = " << a << endl;

    return 0;
}

运行结果:

thread id: 139727756003072, 申请加锁

thread id: 139727756003072, 加锁成功

thread id: 139727747610368, 申请加锁

thread id: 139727756003072, 解锁

thread id: 139727747610368, 加锁成功

thread id: 139727756003072, 申请加锁

thread id: 139727747610368, 解锁

...

感谢浏览

相关推荐
presenttttt7 分钟前
用Python和OpenCV从零搭建一个完整的双目视觉系统(四)
开发语言·python·opencv·计算机视觉
每日出拳老爷子13 分钟前
[C#] 使用TextBox换行失败的原因与解决方案:换用RichTextBox的实战经验
开发语言·c#
半桔16 分钟前
【Linux手册】从接口到管理:Linux文件系统的核心操作指南
android·java·linux·开发语言·面试·系统架构
闻缺陷则喜何志丹16 分钟前
【前缀和 BFS 并集查找】P3127 [USACO15OPEN] Trapped in the Haybales G|省选-
数据结构·c++·前缀和·宽度优先·洛谷·并集查找
nightunderblackcat25 分钟前
新手向:实现ATM模拟系统
java·开发语言·spring boot·spring cloud·tomcat·maven·intellij-idea
开开心心就好27 分钟前
电脑息屏工具,一键黑屏超方便
开发语言·javascript·电脑·scala·erlang·perl
笑衬人心。35 分钟前
Java 17 新特性笔记
java·开发语言·笔记
序属秋秋秋2 小时前
《C++初阶之内存管理》【内存分布 + operator new/delete + 定位new】
开发语言·c++·笔记·学习
ruan1145143 小时前
MySQL4种隔离级别
java·开发语言·mysql
quant_19864 小时前
R语言如何接入实时行情接口
开发语言·经验分享·笔记·python·websocket·金融·r语言