stdthread(2)创建
生活随笔
收集整理的這篇文章主要介紹了
stdthread(2)创建
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.1 函數對象
class hello{ public:void operator()(){std::cout<<"Hello Concurrent World!"<<std::endl;} };std::thread t(hello());//error,編譯器會誤以為是hello函數std::thread t((hello())); //ok std::thread t{hello()}; //ok1.2 例子
using namespace std; void fun1(int n) //初始化構造函數 { cout << "Thread " << n << " executing\n"; n += 10; this_thread::sleep_for(chrono::milliseconds(10)); } void fun2(int & n) //拷貝構造函數 { cout << "Thread " << n << " executing\n"; n += 20; this_thread::sleep_for(chrono::milliseconds(10)); } int test() { int n = 0; thread t1; //t1是一個空thread thread t2(fun1, n + 1); //按照值傳遞 t2.join(); cout << "n=" << n << '\n'; n = 10; thread t3(fun2, ref(n)); //引用 thread t4(move(t3)); //t4執行t3,t3不是thread t4.join(); cout << "n=" << n << '\n'; return 0; }輸出:
Thread 1 executing n=0 Thread 10 executing n=301.3 lambda
void test() { auto fun = [](const char *str) {cout << str << endl; }; thread t1(fun, "hello world!"); thread t2(fun, "hello beijing!"); t1.join();t2.join(); }輸出:
hello world! hello beijing!1.4 可變參數
#include
int show(const char *fun, ...) { va_list ap;//指針 va_start(ap, fun);//開始 vprintf(fun, ap);//調用 va_end(ap); return 0; } int test() { thread t1(show, "%s %d %c %f", "hello world!", 100, 'A', 3.14159); t1.join(); return 0; }輸出:
hello world! 100 A 3.141590總結
以上是生活随笔為你收集整理的stdthread(2)创建的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: stdthread(1)thread概述
- 下一篇: stdthread(3)detach