参考: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;
}