昨天看C++11里的thread构造函数可以写成带入口和参数的形式, 主要看黑体部分。
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
void f1(int n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread " << n << " executing\n";
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void f2(int& n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 2 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int main()
{
int n = 0;
std::thread t1; // t1 is not a thread
std::thread t2(f1, n + 1); // pass by value
std::thread t3(f2, std::ref(n)); // pass by reference
std::thread t4(std::move(t3)); // t4 is now running f2(). t3 is no longer a thread
t2.join();
t4.join();
std::cout << "Final value of n is " << n << '\n';
}
以上来自cppreference。
我就对参数个数不同,它是怎么知道的产生疑问?好吧,有人立刻想到了printf("%s %d %X", a, b,c)这样的东西。于是就上网查了一下怎么使用可变参数的方法。下面的代码是参照百度上的内容:
大体的意思是针对采用入栈方式调用函数,不需要知道几个入参,利用va_list, va_start, va_end这样的宏来告诉编译器哪个是第一个参数,然后自己一个个把参数取出来,听起来还是挺麻烦的,最关键的是自己要去解析各个参数。
PS:如果是类的成员,由于函数的调用方式和普通函数不一样,我还不知道这两者是不是一样。
要包含头文件
#include <iostream>
#include <thread>
#include <stdarg.h>
void HelloWorld(const char * fisrt, ...)
{
va_list argp;
int argno = 0;
char * para;
va_start(argp, fisrt);
while (true)
{
para = va_arg(argp, char*);
if (strcmp(para, "\0") == 0)
{
break;
}
printf("参数 #%d是: %s\n", argno, para);
++argno;
}
va_end(argp);
return;
}
int main()
{
std::thread t(HelloWorld, "This", "is", "a", "DEMO", "\0");
t.join();
t.detach();
system("pause");
return 0;
}
再在CPPReference上看std::thread的其中一个构造函数(其实第一步就应该看这玩意。。。)
explicit thread( Function&& f, Args&&... args );