您的位置:首页 > 编程语言 > C语言/C++

c++11的多线程支持一(线程启动)

2014-01-13 13:28 447 查看
支持多线程编程,是c++11的一个新特性。在语言层面编写多线程程序,程序的可移植性得到很大提高。

新的线程库通过std::thread管理线程的执行,启动线程的方式有两种:

1、以一个函数地址为参数,实例化一个std::thread对象;

2、通过一个类的实例构造一个std::thread对象,用于构建std::thread的类必须实现了operator()方法。

一旦传入的函数返回,线程终止。下面以一个实例说明:

#include <iostream>
#include <thread>

void fun()
{
std::cout << "method one: thread start" << std::endl;
std::cout << "method one: thread stop" << std::endl;
}

class run
{
public:
void operator()()
{
std::cout << "method two: thread start" << std::endl;
std::cout << "method two: thread stop" << std::endl;
}
};

int32_t main()
{
// one method of launching thread
std::thread t_1(fun);
std::cout << "method one: start test thread" << std::endl;
t_1.join();
std::cout << "method one: over" << std::endl;

// the other method of launching thread
run r;
//std::thread t_2(r);  // 1. this actually copies the supplied object into the thread.
std::thread t_2(std::ref(r));  // 2. if you want to use the object you supplied, you can do so by wrapping it in std::ref.
std::cout << "method two: start test thread" << std::endl;
t_2.join();
std::cout << "method two: over" << std::endl;
return 0;
}
执行后,这段代码的输出为:

method one: start test thread

method one: thread start

method one: thread stop

method one: over

method two: start test thread

method two: thread start

method two: thread stop

method two: over
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: