1. 程式人生 > >c++11特性之std::thread--初識

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

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,那麼恭喜你,上面的程式碼你不會執行成功。