多线程学习笔记

1.mutex

mutex是一个用于线程同步的工具,提供一种互斥机制,确保在同一时间只有一个线程可以访问被保护的代码区域,从而避免数据竞争。

基本用法:

#include<mutex>
//定义一个std::mutex对象:
std::mutex myMutex;

锁定和解锁mutex:

myMutexlock();
//临界代码
myMutex.unlock();

使用try_lock()方法尝试锁定mutex,如果失败返回false,成功返回true;

if (myMutex.try_lock()){
    //临界代码
    myMutex.unlock();
}else{
    //未能获取锁}

使用lock_guard进行自动管理:lock_guard会在构造时锁定mutex,这样可以避免手动解锁mutex的麻烦,防止忘记解锁导致死锁。

{
    lock_guard<mutex> guard(myMutex);
    //临界代
}//离开作用域时,guard会自动解锁myMutex

使用unique_lock进行灵活管理:它可以在构造时选择是否锁定mutex,也可以在之后手动锁定或解锁mutex。

unique_lock<mutex> lock(myMutex);
//临界代码
lock.unlock//手动解锁

2.condition_variable

condition_variable 是用于线程间同步的工具,它允许线程等待某个条件满足时再继续执行。通常情况下,std::condition_variable 与 std::mutex 一起使用,一个线程等待某个条件,而另一个线程在条件满足时通知等待的线程。

等待线程:condition_variable::wait 等待某个线程满足。

通知线程:condition_variable::notify_one 或condition_variable::notify_all 通知等待的线程条件已满足。

典型用法:一个或多个线程等待某个条件满足。另一个线程在满足某些条件后,通知等待的线程继续执行。

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

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void workerThread() {
    std::cout << "Worker thread is waiting...\n";
    
    // 锁住互斥量
    std::unique_lock<std::mutex> lock(mtx);
    
    // 等待条件变量,直到 ready 为 true
    cv.wait(lock, []{ return ready; });
    
    // 条件满足后继续执行
    std::cout << "Worker thread proceeds after condition is met.\n";
}

void mainThread() {
    std::cout << "Main thread prepares data...\n";
    
    // 模拟一些耗时操作
    std::this_thread::sleep_for(std::chrono::seconds(2));
    
    // 准备就绪,设置 ready 为 true
    {
        std::lock_guard<std::mutex> lock(mtx);
        ready = true;
    }
    
    // 通知等待的线程
    std::cout << "Main thread notifies worker thread.\n";
    cv.notify_one();
}

int main() {
    // 创建线程
    std::thread t1(workerThread);
    std::thread t2(mainThread);
    
    // 等待线程结束
    t1.join();
    t2.join();

    return 0;
}

3.thread 

thread是c++标准库中用于创建和管理线程的类,使用thread可以方便地建立线程并执行并发任务。

例子:

#include <thread>
using namespace std;

void test(){
    //线程执行代码
    cout<< "hello from thread!"<<endl;
}
int main(){
    //创建线程
    thread t(test);
    t.join();
    return 0; }

传递参数:

可以通过 thread 传递参数给线程函数。默认情况下,参数会以拷贝的方式传递给线程函数,如果需要传递引用,则需要使用ref。

void threadFunction(int x, const std::string& str) {
    std::cout << "Parameter: " << x << ", " << str << std::endl;
}

int main() {
    int param = 10;
    std::string strParam = "Hello";

    // 创建线程并传递参数
    std::thread t(threadFunction, param, std::ref(strParam));

    // 等待线程完成
    t.join();

    return 0;
}

线程管理:

join():等待线程完成执行。调用join()后,当前线程会被阻塞,直到被join的线程执行完毕。

detach():将线程与当前线程分离,使得线程可以在后面独立执行,调用detach()后,线程的生命周期将不再由创建它的线程管理,不能对该线程调用join()。

检查线程是否可被join,可使用joinable()来检查线程是否可被join。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

mmasterer

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

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

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

打赏作者

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

抵扣说明:

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

余额充值