c++11特性之std::thread--进阶二

继续C++11的std::thread之旅!

下面讨论如何给线程传递参数
这个例子是传递一个string

#include <iostream>
#include <thread>
#include <string>

void thread_function(std::string s)
{
    std::cout << "thread function ";
    std::cout << "message is = " << s << std::endl;
}

int main()
{
    std::string s = "Kathy Perry";
    std::thread t(&thread_function, s);
    std::cout << "main thread message = " << s << std::endl;
    t.join();
    return 0;
}

如果运行,我们可以从输出结果看出传递成功了。

良好编程习惯的人都知道 传递引用的效率更高,那么我们该如何做呢?
你也许会这样写:

void thread_function(std::string &s)
{
    std::cout << "thread function ";
    std::cout << "message is = " << s << std::endl;
    s = "Justin Beaver";
}

为了确认是否传递了引用?我们在线程函数后更改这个参数,但是我们可以看到,输出结果并没有变化,即不是传递的引用。

事实上, 依然是按值传递而不是引用。为了达到目的,我们可以这么做:

std::thread t(&thread_function, std::ref(s));

这不是唯一的方法:

我们可以使用move():

std::thread t(&thread_function, std::move(s));

接下来呢,我们就要将一下线程的复制吧!!
以下代码编译通过不了:

#include <iostream>
#include <thread>

void thread_function()
{
    std::cout << "thread function\n";
}

int main()
{
    std::thread t(&thread_function);
    std::cout << "main thread\n";
    std::thread t2 = t;

    t2.join();

    return 0;
}

但是别着急,稍稍修改:

include <iostream>
#include <thread>

void thread_function()
{
    std::cout << "thread function\n";
}

int main()
{
    std::thread t(&thread_function);
    std::cout << "main thread\n";
    std::thread t2 = move(t);

    t2.join();

    return 0;
}

大功告成!!!

再聊一个成员函数吧 std::thread::get_id();

int main()
{
    std::string s = "Kathy Perry";
    std::thread t(&thread_function, std::move(s));
    std::cout << "main thread message = " << s << std::endl;

    std::cout << "main thread id = " << std::this_thread::get_id() << std::endl;
    std::cout << "child thread id = " << t.get_id() << std::endl;

    t.join();
    return 0;
}
Output:

thread function message is = Kathy Perry
main thread message =
main thread id = 1208
child thread id = 5224

聊一聊std::thread::hardware_concurrency()
获得当前多少个线程:

int main()
{
    std::cout << "Number of threads = " 
              <<  std::thread::hardware_concurrency() << std::endl;
    return 0;
}
//输出:

Number of threads = 2

之前介绍过c++11的lambda表达式
我们可以这样使用:

int main()
{
    std::thread t([]()
    {
        std::cout << "thread function\n";
    }
    );
    std::cout << "main thread\n";
    t.join();     // main thread waits for t to finish
    return 0;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一苇渡江694

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值