stdthread创建
Posted thefist11
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了stdthread创建相关的知识,希望对你有一定的参考价值。
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 thello(); //ok
1.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=30
1.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创建的主要内容,如果未能解决你的问题,请参考以下文章
stdthread并发recursive_mutex 递归锁