c++11线程类里,传递参数给可调用对象或函数,基本上就是简单地将额外的参数传递给 std::thread 构造函数。但重要的是,参数会以默认的方式被复制到内部存储空间,在那里新线程可以访问它们,即使函数中的相应参数期待着引用。如:
#include <stdio.h>
#include <stdlib.h>
#include <thread>
#include <string>
#include <sys/syscall.h>
#include <unistd.h>
void funcProc(int &value)
{
printf("in new thread %lu, old value = %d\n", syscall(SYS_gettid), value);
value = 250;
}
void funcProc1(int *value)
{
printf("in new thread %lu, old value = %d\n", syscall(SYS_gettid), *value);
*value = 350;
}
void funcProc2(char *str, int size)
{
printf("in new thread %lu, old str = %d\n", syscall(SYS_gettid), *str);
snprintf(str, size, "%s", "just a test");
}
int main()
{
int value = 100;
std::thread task(funcProc, std::ref(value));
task.join();
printf("value = %d\n", value);
std::thread task1(funcProc1, &value);
task1.join();
printf("value = %d\n", value);
char str[24] = "init";
std::thread task2(funcProc2, str, 24);
task2.join();
printf("str = %s\n", str);
return 0;
}
要实现函数所期待的引用,则需要用到 std::ref(),而传递指针,我们可以正常传递,其运行结果如下: