【c++】线程thread类

thread类是c++11的新特性。

特点:
std::thread 使用函数作为参数,同时可以为函数接受参数,数目不定。
std::thread 和其他的 std 类一样,主要是提供给我们使用,而不是供我们继承。

std::thread的第一个参数是线程函数名,后面的参数是传给线程函数的参数,当一个std::thread对象被创建后(默认状态下joinable),在对象被析构前必须调用其成员函数join()来等待线程执行结束并释放资源 或者 调用其成员函数detach()将线程分离(独立),此时线程执行完后会自己释放资源

使用范例:(file: main1.cpp)

/***********************************
author:arvik
email:1216601195@qq.com
csdn:http://blog.csdn.net/u012819339
************************************/
#include <iostream>
#include <thread>
#include <string>

using namespace std;
class init
{
public:
        void hello(void) const {cout<<"hello"<<endl;}
        void hello(string str) const {cout<<"hello,"<<str<<endl;}
        void hello(int i, string str) const
        {
                while(i--)
                {
                        cout<<i<<": ";
                        this->hello(str);
                }
        }
};

void fun(int a, char b)
{
        while(a--)
        {
                cout<<a<<": only hello!, b:"<<b<<endl;
        }
}

int main()
{
        init myin;
        string mystr = "world";
        thread th([myin, mystr](){myin.hello(4, mystr);});
        th.detach();

        cout<<"====================="<<endl;
        thread *mypt = new thread(fun, 2, 't');
        mypt->join();
        delete mypt;

        return 0;
}

gcc(版本5.3.1)编译,添加 -std=c++11 以及 -lpthread

c++ -o t1 main1.cpp -std=c++11 -lpthread

执行结果:

=====================
1: only hello!, b:t
0: only hello!, b:t
3: hello,world
2: hello,world
1: hello,world
0: hello,world

(本例子也是对博客 【c++】lambda表达式 例子的补充。)

std::thread还有其他成员函数:
get_id :获取线程ID
joinable:检查线程是否可被join
join:join线程
detach:Detach线程
swap:Swap线程
nativa_handle:返回 native handle。
hadrware_concurrency[static]:检测硬件并发特性

跟std::thread经常搭配使用的还有std::mutex,std::lock_guard 后面的博客抽时间记录

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值