C++线程安全方法

C++有以下方法可以保护线程安全

1 互斥量。
2 读写锁

3 原子操作
4 条件变量
5 线程本地存储 

一些函数调用如下:

1 互斥量

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

std::mutex g_mutex;  
int g_counter = 0;   

void incrementCounter()
{
    std::lock_guard<std::mutex> lock(g_mutex); 
    ++g_counter;
}

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

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

    std::cout << "g_counter = " << g_counter << std::endl;

    return 0;
}

2 读写锁

#include <iostream>
#include <thread>
#include <shared_mutex>

std::shared_mutex g_mutex;  
int g_counter = 0;   

void incrementCounter()
{
    std::unique_lock<std::shared_mutex> lock(g_mutex); //写锁
    ++g_counter;
}

void readCounter()
{
    std::shared_lock<std::shared_mutex> lock(g_mutex); //读锁,读锁可以共享
    std::cout << "g_counter = " << g_counter << std::endl;
}

int main()
{
    std::thread t1(incrementCounter);
    std::thread t2(readCounter);

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

    return 0;
}

3 原子操作

#include <iostream>
#include <thread>
#include <atomic>

std::atomic<int> g_counter{0};  // 原子变量

void incrementCounter()
{
    ++g_counter;
}

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

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

    std::cout << "g_counter = " << g_counter.load() << std::endl;

    return 0;
}

4 条件变量

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

std::mutex g_mutex;
std::condition_variable g_cv;
bool g_flag = false;

void thread1()
{
    std::unique_lock<std::mutex> lock(g_mutex);
    g_flag = true;
    g_cv.notify_one();  // 通知线程 2
}

void thread2()
{
    std::unique_lock<std::mutex> lock(g_mutex);
    while (!g_flag)
    {
        g_cv.wait(lock);  // 等待通知
    }
    std::cout << "thread 2 finished" << std::endl;
}

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

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

    return 0;
}

5 线程本地存储

#include <iostream>
#include <thread>

thread_local int g_counter = 0;  // 线程本地变量

void incrementCounter()
{
    ++g_counter;
    std::cout << std::this_thread::get_id() << ": " << g_counter << std::endl;
}

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

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

    return 0;
}

线程本地存储确保两个线程的变量互不干扰

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值