c++11 std::thread

c中同样适用的pthread库就不在赘述,只讨论std::thread

C++11中加入的thread,需要编译器支持至少gcc4.7.0以上。编译安装gcc注意参考网上文章。

 

#include <unistd.h>
#include <iostream>
#include <thread>

//using namespace std;

void thread_func()
{
    std::cout << "this thread = " << std::this_thread::get_id() << std::endl;
}

int main()
{
    std::thread thread1(thread_func);
    thread1.join();
    return 0;
}
View Code

1、++ thread.cc -Wall -pthread -std=c++11 -o thread//std::pthread 编译时,还需要加-pthread。。。s

使用std::this_thread::get_id() 获得threadid。http://www.cplusplus.com/reference/thread/this_thread/

2、std::thread的执行体并不要求必须是普通的函数,任何可调用(Callable)的对象都是可以的

使用lambda表达式:std::thread thread1([](int a, int b){std::cout << a << "+" << b << "=" << a + b<< std::endl;}, 1, 2);

3、等待线程结束

线程分为分离或者joinable状态,thread有一个成员函数joinable可以判断是否可以joinable。在被析构时如果joiable == true会导致

terminat()被调用。

默认构造函数对象不代表任何线程,所以joinable是false的;调用过join的是false;调用过detach的;

4、除了std::thread的成员函数外在std::this_thread命名空间中也定义了一系列函数用于管理当前线程。

 

 

参考文献:https://blog.poxiao.me/p/multi-threading-in-cpp11-part-1-thread-and-future/

 

posted @ 2018-03-02 17:14  Hi!gc  阅读(197)  评论(0编辑  收藏  举报