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

c++11特性之std::thread--初识

2015-11-02 21:51 330 查看
C++11中已经拥有了一个更好用的用于线程操作的类std::thread。

默认构造函数:

thread() noexcept;

构造一个任何线程不执行的线程对象。

初始化函数:

template <class Fn, class... Args>
explicit thread (Fn&& fn, Args&&... args);


构造一个线程对象,可以开启线程执行

新执行的线程调用函数fn,并传递args作为参数

fn

可以指向函数,指向成员,或是移动构造函数

args…

传递给fn的参数,这些参数可以移动赋值构造。如果fn是一个成员指针,那么第一个args参数就必须是一个对象,或是引用,或是指向该对象的指针。

拷贝构造函数:

thread (const thread&) = delete;

删除构造的线程

现在介绍几个成员函数:

std::thread::join

该函数返回时,线程执行完成。

当 a thread 调用Join方法的时候,MainThread 就被停止执行,直到 a thread 线程执行完毕。

#include <iostream>       // std::cout
#include <thread>         // std::thread, std::this_thread::sleep_for
#include <chrono>         // std::chrono::seconds

void pause_thread(int n)
{
std::this_thread::sleep_for (std::chrono::seconds(n));
std::cout << "pause of " << n << " seconds ended\n";
}

int main()
{
std::cout << "Spawning 3 threads...\n";
std::thread t1 (pause_thread,1);
std::thread t2 (pause_thread,2);
std::thread t3 (pause_thread,3);
std::cout << "Done spawning threads. Now waiting for them to join:\n";
t1.join();
t2.join();
t3.join();
std::cout << "All threads joined!\n";

return 0;
}

//输出
Output (after 3 seconds):
Spawning 3 threads...
Done spawning threads. Now waiting for them to join:
pause of 1 seconds ended
pause of 2 seconds ended
pause of 3 seconds ended
All threads joined!


std::thread::detach

分离线程的对象,使它们从彼此独立地执行所表示的线程。这两个线程继续没有阻止,也没有以任何方式同步。注意,当任一结束执行,其资源被释放。

#include <iostream>       // std::cout
#include <thread>         // std::thread, std::this_thread::sleep_for
#include <chrono>         // std::chrono::seconds

void pause_thread(int n)
{
std::this_thread::sleep_for (std::chrono::seconds(n));
std::cout << "pause of " << n << " seconds ended\n";
}

int main()
{
std::cout << "Spawning and detaching 3 threads...\n";
std::thread (pause_thread,1).detach();
std::thread (pause_thread,2).detach();
std::thread (pause_thread,3).detach();
std::cout << "Done spawning threads.\n";

std::cout << "(the main thread will now pause for 5 seconds)\n";
// give the detached threads time to finish (but not guaranteed!):
pause_thread(5);
return 0;
}
//输出
Output (after 5 seconds):
Spawning and detaching 3 threads...
Done spawning threads.
(the main thread will now pause for 5 seconds)
pause of 1 seconds ended
pause of 2 seconds ended
pause of 3 seconds ended
pause of 5 seconds ended


上一段代码 深入理解:

#include <iostream>
#include <thread>

using namespace std;

class Foo
{
void bar_i() { cout << "hello" << endl; }

public:
void bar()
{
auto func = std::bind(&Foo::bar_i, this);
std::thread t(&Foo::bar_i, std::ref(*this));
t.join();
}
};

int main()
{
Foo f;
f.bar();
}


如果你使用的是VS2015,那么恭喜你,上面的代码你不会运行成功。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: