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

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

时间:2015-11-04 00:48:42      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:

继续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;
}

版权声明:本文为博主原创文章,未经博主允许不得转载。

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

标签:

原文地址:http://blog.csdn.net/wangshubo1989/article/details/49624669

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