stdthread(2)创建
生活随笔
收集整理的這篇文章主要介紹了
stdthread(2)创建
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.1 函數(shù)對(duì)象
class hello{ public:void operator()(){std::cout<<"Hello Concurrent World!"<<std::endl;} };std::thread t(hello());//error,編譯器會(huì)誤以為是hello函數(shù)std::thread t((hello())); //ok std::thread t{hello()}; //ok1.2 例子
using namespace std; void fun1(int n) //初始化構(gòu)造函數(shù) { cout << "Thread " << n << " executing\n"; n += 10; this_thread::sleep_for(chrono::milliseconds(10)); } void fun2(int & n) //拷貝構(gòu)造函數(shù) { cout << "Thread " << n << " executing\n"; n += 20; this_thread::sleep_for(chrono::milliseconds(10)); } int test() { int n = 0; thread t1; //t1是一個(gè)空thread thread t2(fun1, n + 1); //按照值傳遞 t2.join(); cout << "n=" << n << '\n'; n = 10; thread t3(fun2, ref(n)); //引用 thread t4(move(t3)); //t4執(zhí)行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 可變參數(shù)
#include
int show(const char *fun, ...) { va_list ap;//指針 va_start(ap, fun);//開(kāi)始 vprintf(fun, ap);//調(diào)用 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總結(jié)
以上是生活随笔為你收集整理的stdthread(2)创建的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: stdthread(1)thread概述
- 下一篇: stdthread(3)detach