码迷,mamicode.com
首页 > 编程语言 > 详细

c++11 std::thread

时间:2018-03-02 18:43:51      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:span   ace   构造函数   hid   style   this   one   pen   stream   

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/

 

c++11 std::thread

标签:span   ace   构造函数   hid   style   this   one   pen   stream   

原文地址:https://www.cnblogs.com/wocgcow/p/8494225.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!