线程传参
passing arguments to threads
给thread传参很简单,直接将callable object/function需要的参数当做额外的参数传给std:thread constructor就可以了,所有传入的参数都会被copy给新的thread:
#include <iostream>
#include <string>
#include <thread>
void func(int x, std::string y){
...
}
int main(){
int i = 1;
std::string str = "sample";
std::thread t(func, i, str);
t.join();
return 0;
}
caveat:
pass stack-located local variable to threads
尽量不要给thread传输在stack上的local variable,因为很有可能这个local variable会因为out of scope而被删除。
#include <iostream>
#include <thread>
void func(int* p){
std::cout << "inside func " << p << std::endl;
std::chrono::milliseconds dura(1000);
std::this_thread::sleep_for(dura);
*p=2;
}
void start(){
int i = 10;
std::cout <<