c++11 线程学习之启动线程

       使用c++11 来创建线程,首先必须包含头文件#include <thread>,管理线程的函数和类通常声明在这个头文件里,那些受保护的共享数据声明在其他头文件里。下边为简单的创建线程的方法实例代码:

#include <iostream>
#include <thread>

// 入口函数
void hello()
{
    std::cout<<"Hello Concurrent World\n";
}

int main()
{
    std::thread t(hello);

    t.join();   // 等待子线程结束
}
# --------CMakeLists.txt
project(testthread)
cmake_minimum_required(VERSION 2.8)

#添加c++11编译选项
add_compile_options(-std=c++11)
aux_source_directory(. SRC_LIST)
add_executable(${PROJECT_NAME} ${SRC_LIST})

# 链接pthread库
TARGET_LINK_LIBRARIES(${PROJECT_NAME} pthread)

    上边为创建线程最简单的方法,线程入口函数没有参数,返回值为void,该函数也只是执行一个简单的输出。接下来,我们介绍另一种创建线程的方式:As with much of the C++ Standard Library, std::thread works with any

callable type, so you can pass an instance of a class with a function call operator to the std::thread constructor instead:

实例代码如下:

#include <iostream>
#include <thread>

class background_task
{
public:
    // 要求提供了一个名称为operator()的函数
    int operator()() const
    {
        std::cout << "Hello Concurrent World\n";
    }
};

int main()
{
    background_task f;

    // 将该类命名对象作为参数传入的方式,开启一个线程
    std::thread t(f);

    t.join();   // 等待子线程结束
}

        请注意: 如果传入给thread对象的参数是一个临时对象而不是命名对象类似f,则无法启动一个新的线程,如下所示:

std::thread my_thread(background_task());

这样就变成了函数声明了。

        那么,我们有没有办法可以避免这种容易失误的情况呢,答案是肯定的。

第一种:通过多添加一层括号的方式,这样可以避免编译器将其解释为声明

std::thread my_thread((background_task()));

第二种:使用在c++11中,大括号的初始化方式

std::thread t{background_task()};

还有一种是使用c++11的新特性lambda表达式来处理这一情况,后边我们再稍微详细介绍。

      

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值