C++11 中线程同步的基本操作——互斥锁 lock()

1. 例子

1. 不加 互斥锁

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

volatile int nunber(0);
std::mutex mtx;

void thrfunc() {
    for (int i = 0; i < 1000000; i++) {
       // mtx.lock();
        ++counter;
        //mtx.unlock();
    }
}


int main(int argc, const char* argv[]) {
    std::thread threads[10];

    for (int i = 0; i < 10; ++i)
        threads[i] = std::thread(thrfunc);

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

    std::cout << "count to " << counter << " Succeddfully." << std::endl;

    return 0;
}
1. 结果(在 VS 2019 不是 1,000,000):

在这里插入图片描述

2. 结果报错 (g++ 4.7
terminate called after throwing an instance of 'std::system_error'
  what():  Enable multithreading to use std::thread: Operation not permitted
Aborted



2. 加上 互斥锁

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

volatile int number(0);
std::mutex mtx;


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


int main(int argc, const char* argv[]) {
    std::thread threads[10];

    for (int i = 0; i < 10; ++i)
        threads[i] = std::thread(testfunc);

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

    std::cout << "count to " << number << " Succeddfully." << std::endl;

    return 0;
}
  • 结果就是我们想要的结果:
    在这里插入图片描述

2. 原因

典型的 生产者-消费者 模型(此处 进程线程 的原理是一样的)

  • 根源:因为 counter++ 不是 原子操作
    在这里插入图片描述

  • 解决办法:(上锁

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

volatile int number(0);
std::mutex mtx;


void testfunc() {
    for (int i = 0; i < 1000000; i++) {
        mtx.lock();				// 上锁
        ++number;
        mtx.unlock();			// 开锁
    }
}


int main(int argc, const char* argv[]) {
    std::thread threads[10];

    for (int i = 0; i < 10; ++i)
        threads[i] = std::thread(testfunc);

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

    std::cout << "count to " << number << " Succeddfully." << std::endl;

    return 0;
}

在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值