C++ 多线程学习(二) 互斥锁std::mutex

在多线程中经常会遇到多个线程同时修改同一个变量的情况,这个时候如果不对线程进行一定约束,很可能会导致意想不到的结果。例如有两个线程1和线程2,线程2的输入是线程1的结果。很显然如果在主线程中同时开启了线程1和线程2,它们是同时运行的,会直接导致程序的崩溃。所以线程同步锁应运而生,当遇到它时它会让当前线程独占某个变量,其它同样需要修改该变量的线程此时只能处于等待状态,等到当前线程结束之后,线程独占锁自动释放,其它线程可以修改内容。

// mutex example
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex

std::mutex mtx;           // mutex for critical section
int counter=0;
void print_block (int n) {
  // critical section (exclusive access to std::cout signaled by locking mtx):
 // mtx.lock();
  for (int i=0; i<n; ++i) { 
 // std::cout << '\n';
     std::this_thread::sleep_for(std::chrono::milliseconds(1));
 counter++;}
 // mtx.unlock();
}

int main ()
{
  std::thread th1 (print_block,50);
  std::thread th2 (print_block,50);

  th1.join();
  th2.join();
  
  std::cout << "counter:" << counter << std::endl;
  return 0;
}

#include<thread>  
#include<mutex>  
using namespace std;  
const int N = 100000000;  
int num(0);  
mutex m;  
void run()  
{  
    for (int i = 0; i < N; i++)  
    {  
        m.lock();  
        num++;  
        m.unlock();  
    }  
}  
int main()  
{  
    clock_t start = clock();  
    thread t1(run);  
    thread t2(run);  
    t1.join();  
    t2.join();  
    clock_t end = clock();  
    cout << "num=" << num << ",用时 " << end - start << " ms" << endl;  
    return 0;  
}  
运行结果:  
num=200000000,用时 128323 ms

加锁后计算正确,但由于加锁和解锁导致时间增加;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值