在windows上面启线程时,用的是windows的API,前辈说可以去学一下C++11 提供的线程库,比较方便灵活。下面就介绍一下thread的用法。
std::thread::thread
thread() noexcept; |
(1) | (C++11 起) |
thread( thread&& other ) noexcept; |
(2) | (C++11 起) |
template< class Function, class... Args > |
(3) | (C++11 起) |
thread(const thread&) = delete; |
(4) | (C++11 起) |
构造新的 thread
对象。
1) 构造不表示线程的新 thread
对象。
2) 移动构造函数。构造表示曾为 other
所表示的执行线程的 thread
对象。此调用后 other
不再表示执行线程。
3) 构造新的 std::thread
对象并将它与执行线程关联。新的执行线程开始执行
4) 复制构造函数被删除; thread
不可复制。没有两个 std::thread
对象可表示同一执行线程。
std::thread::~thread
~thread(); |
(C++11 起) |
在下列操作后 thread 对象无关联的线程(从而可安全销毁)
std::thread::operator=
thread& operator=( thread&& other ) noexcept; |
(1) | (C++11 起) |
这个例子是借鉴cppreference.com这个网站上面的,我详细的分析一下这个例子。
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
void f1(int n){
for (int i = 0; i < 2; ++i) {
std::cout << "Thread 1 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void f2(int& n){
for (int i = 0; i < 2; ++i) {
std::cout << "Thread 2 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
class foo{
public:
void bar(){
for (int i = 0; i < 2; ++i) {
std::cout << "Thread 3 executing\n&#