std::thread::thread
文章目录
thread() noexcept; | (1)(since C++11) |
thread(thread&& other)noexcept; | (2)(since C++11) |
template < class Function, class... args > explicit thread (Function& fn, Args &&... args); |
(3)(since C++11) |
thread(const thread&)=delete; | (4)(since C++11) |
构造新的 thread 对象。
(1)默认构造函数。创建一个不代表任何可执行线程的 thread 对象。
(2)move 构造函数。构造一个 thread 对象,该对象会获取 other 表示的线程,该操作不会以任何方式影响被移动线程的执行,它只是传输其处理程序。在此调用后,other 就不再是一个可执行的线程。
(3)创建一个 thread 对象并将其与执行线程关联,新的执行线程调用 Function 并通过 args 传递参数。
(4)线程不可被 copy (没弄明白)
创建线程
#include <iostream>
#include <thread>
using namespace std;
void f1()
{
for (int i = 0; i < 5; i++)
{
cout << "--------------" << endl;
}
}
void f2()
{
for (int i = 0; i < 5; i++)
{
cout << "++++++++++++++" << endl;
}
}
int main()
{
thread t1; //t1 is not a thread
thread t2(f1); //t2 is a thread
thread t3(f2);
thread t4(move(t3)); //t4 is now running f2(), t3 is no longer is a thread
t2.join();
t4.join();
return 0;
}
类与线程
#include <iostream>
#include <thread>
using namespace std;
class foo {
public:
void bar()
{
for (int i = 0; i < 5; i++)
{
cout << "--------------" << endl;
}
}
};
class baz {
public:
void operator()()
{
for (int i = 0; i < 5; i++)
{
cout << "++++++++++++++" << endl;
}