c++11 互斥锁

参考:https://blog.csdn.net/krais_wk/article/details/81095899

看完linux c下的多线程编程之后,发现c++11引入了多线程的标准库,可以支持跨平台的开发,仿照写了一个互斥锁的程序。

提示!:把类成员函数作为线程函数时,第一个参数是成员函数,第二个参数是类对象,剩下的是函数参数。另外,我遇到最麻烦的,如果类声明了构造函数,哪怕什么都没有,也要写出来,否则会出错。

//
//  main.cpp
//  互斥锁
//
//  Created by 蓝猫 on 2018/12/18.
//  Copyright © 2018年 蓝猫. All rights reserved.
//

#include <iostream>
#include <mutex>
#include <thread>
#include <unistd.h>
#include <stack>
using std::stack;

class Hello
{
 private:
    std::mutex mutex_t;
    int x;
public:
    Hello(){x=0;};//构造方法声明必须写 不然把类成员传入线程函数时会报错!!!!!!!!!!
    void run1()
    {
        sleep(1);
        mutex_t.lock();
        for(int i=0;i<5;i++)
        {
            x++;
            std::cout<<"thread1:x="<<x<<std::endl;
        }
       mutex_t.unlock();
    }
  void run2()
    {
        mutex_t.lock();
        for(int i=0;i<5;i++)
        {
            x++;
            std::cout<<"thread2:x="<<x<<std::endl;
        }
        mutex_t.unlock();
    }
};
int main(int argc, const char * argv[]) {
   
    //std::thread thread1(std::mem_fn(&Solution::run1),s1,x);
    //std::thread thread2(std::mem_fn(&Solution::run2),s2,x);
    //fun();
    Hello s1;
    std::thread thread1(&Hello::run1,&s1);
    std::thread thread2(&Hello::run2,&s1);
    thread1.join();
    thread2.join();
    
    
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值