C++11线程注意点

1 。拷贝构造函数

thread(const thread&) = delete;
拷贝构造函数被禁用,std::thread对象不可拷贝构造

2 。Move构造函数

thread(thread&& x)noexcept
调用成功原来x不再是std::thread对象

void threadFun(int& a)
{
    cout << "this is thread fun !" << endl;
}

int value = 2;
thread t1(threadFun, std::ref(value));
thread t2(std::move(t1));
t2.join();

3。get_id()

获取线程ID,返回类型std::thread::id对象。

thread t1(threadFun);
thread::id threadId = t1.get_id();
cout << "线程ID:" << threadId << endl;

//threadId转换成整形值,所需头文件<sstream>
ostringstream   oss;
oss << t1.get_id();
string strId = oss.str();
unsigned long long tid = stoull(strId);
cout << "线程ID:" << tid << endl;

4。 创建线程,引用传参 std::ref()

void threadFun1(int& v)
{
    cout << "this is thread fun1 !" << endl;
    cout << v << endl;
}

int main()
{
    int value = 6;
    thread t1(threadFun1, std::ref(value));
    t1.join();

    getchar();
    return 1;
}

5。创建线程,函数对象参数格式

 struct fun_obj

{

void operator() () { do_something(); };

}

std::thread td(fun_obj());//函数声明

std::thread td((fun_obj()));//创建线程

std::thread td{ fun_o bj() };//创建线程

fun_obj  obj;

std::thread td(obj);//创建线程

6。线程参数:函数对象、引用、字符串(字面值/char*/string隐式转换问题) 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值