Passing Arguments to Threads

Passing Arguments to Threads

要想传递参数给线程相关的回调对象或者函数,可以通过在std::thread的构造器中传递,默认情况下,所有的参数都会被拷贝进线程的内部存储。

Passing simple arguments to a std::thread in C++11

1
2
3
4
5
6
7
8
9
void threadCallback(int x, std::string str){ ... }
int main()
{
int x = 10;
std::string str = "Sample String";
std::thread threadObj(threadCallback, x, str);
threadObj.join();
return 0;
}

How not to pass arguments to threads in C++11

不要将变量的地址从本地栈传递给线程的回调函数,因为线程1中的局部变量可能已经不在作用域,但线程2访问了它的非法地址。

1
2
3
4
5
6
7
void newThreadCallback(int * p) { ... }
void startNewThread()
{
int i = 10;
std::thread t(newThreadCallback,&i);
t.detach();
}

同样要注意的是,不要把指向位于堆上内存的指针传递进线程,因为有可能在新线程访问之前,原线程已经删除了该内存。

1
2
3
4
5
6
7
8
9
10
void newThreadCallback(int * p) { ... }
void startNewThread()
{
int * p = new int();
*p = 10;
std::thread t(newThreadCallback,p);
t.detach();
delete p;
p = NULL;
}

How to pass references to std::thread in C++11

如果是传递引用,参数会被拷贝进线程栈:

1
2
3
4
5
6
7
void threadCallback(int const & x) {} //change x
int main()
{
std::thread threadObj(threadCallback, x);
threadObj.join();
return 0;
}

这种情况下,线程内部对于x的改动,外部域是看不到的。因为线程函数threadCallback中的x引用了在新线程堆栈中复制的临时值。

如果想要外部也是可视的,可以使用std::ref。

1
2
3
4
5
6
7
void threadCallback(int const & x) {} //hange x
int main()
{
std::thread threadObj(threadCallback, std::ref(x));
threadObj.join();
return 0;
}

Assigning pointer to member function of a class as thread function

将指向类成员函数的指针传递给回调函数,并将指针作为第二个参数传递给object:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <thread>
class DummyClass {
public:
DummyClass()
{}
DummyClass(const DummyClass & obj)
{}
void sampleMemberFunction(int x)
{
std::cout<<"Inside sampleMemberFunction "<<x<<std::endl;
}
};
int main() {

DummyClass dummyObj;
int x = 10;
std::thread threadObj(&DummyClass::sampleMemberFunction,&dummyObj, x);
threadObj.join();
return 0;
}