c++11的多线程支持一(线程启动)

支持多线程编程,是c++11的一个新特性。在语言层面编写多线程程序,程序的可移植性得到很大提高。

新的线程库通过std::thread管理线程的执行,启动线程的方式有两种:

1、以一个函数地址为参数,实例化一个std::thread对象;

2、通过一个类的实例构造一个std::thread对象,用于构建std::thread的类必须实现了operator()方法。

一旦传入的函数返回,线程终止。下面以一个实例说明:

#include <iostream>
#include <thread>

void fun()
{
    std::cout << "method one: thread start" << std::endl;
    std::cout << "method one: thread stop" << std::endl;
}

class run
{
public:
    void operator()()
    {
        std::cout << "method two: thread start" << std::endl;
        std::cout << "method two: thread stop" << std::endl;
    }
};

int32_t main()
{
    // one method of launching thread
    std::thread t_1(fun);
    std::cout << "method one: start test thread" << std::endl;
    t_1.join();
    std::cout << "method one: over" << std::endl;

    // the other method of launching thread
    run r;
    //std::thread t_2(r);  // 1. this actually copies the supplied object into the thread.
    std::thread t_2(std::ref(r));  // 2. if you want to use the object you supplied, you can do so by wrapping it in std::ref.
    std::cout << "method two: start test thread" << std::endl;
    t_2.join();
    std::cout << "method two: over" << std::endl;
    return 0;
}
执行后,这段代码的输出为:

method one: start test thread
method one: thread start
method one: thread stop
method one: over
method two: start test thread
method two: thread start
method two: thread stop
method two: over

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值