C++11多线程编程

1.初识多线程

#include<thread>
using namespace std;

int main()
{
    thread t(fun);
    //t.detach; 子线程由C++运行时库接管,主线程和进程可能先于次线程先退出,导致次线程结果打印不到屏幕
    if(t.joinable){
        t.join;//主线程等待该子线程运行结束
    }
    return 0;
}

2.线程接受函数对象

#include<thread>
using namespace std;

//无参函数对象
class TA{
public:
    void operator()(){
        cout << "hello" << endl;
    }
};

int main()
{
    TA ta;
    thread t(ta);
    if(t.joinable){
        t.join;//主线程等待该子线程运行结束
    }
    return 0;
}
#include<thread>
using namespace std;

//有参函数对象
class TA{
public:
    int m_i;
    TA(int& i) : m_i(i){}
    void operator()(){
        cout << m_i << endl;
    }
};

int main()
{
    int i=1;
    TA ta(i);
    thread t(ta);//调用TA的拷贝构造函数
    if(t.joinable){
        t.join;//主线程等待该子线程运行结束
    }
    return 0;
}

3.线程接受lambda表达式

auto fun1 = []{ cout << "hello" << endl;};
thread t(fun1);

4.线程接受带参函数

void myprint(const int& i, char* buf){
    cout << i << endl;
    cout << buf << endl;
}

int main(){
    int i=1;
    int& m_i=i;
    char* buf = "hello";
    thread t(myprint, i, buf);//虽然myprint接受的是引用,但是因为这里没有使用std::ref传参,myprint处理的还是只是i的拷贝
    t.join();
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值