How do I pass data to different threads
Suppose If I create 5 thre开发者_运维百科ads through CreateThread()
. I'll need to pass intergers 1, 2, 3, 4, 5 to each thread but I also have to pass a this
pointer. Neither I can pass more than one argument because CreateThread
function takes only one, nor I can create a member variable in class because that will be shared between the threads. How can do it and how much data can a thread stack have?
Define a struct and pass an object of this struct.
The struct can be this:
struct ThreadContext
{
MyClass *m_this;
int m_int;
//add more members you need to pass more data
};
Then you can do this:
for ( int i = 0 ; i < 5 ; i++ )
{
ThreadContext *ctx = new ThreadContext();
ctx->m_this = this;
ctx->m_int = i ;
CreateThread(...., ThreadProc, ctx, ...);
}
Make sure that the object you pass to each thread is different object. That is why I used new
and created an object for each thread. And then inside the ThreadFunc
, use static_cast
as:
DWORD WINAPI ThreadProc(LPVOID lpParameter)
{
ThreadContext *ctx = static_cast<ThreadContext*>(lpParameter);
//use ctx
//...
//at the end of the thread, deallocate the memory!
delete ctx;
}
Or alternatively, you could maintain a std::vector<ThreadContext>
as member data of MyClass
.
Maybe create a new struct containing a this pointer and an integer, and pass that to the thread, extracting these contents appropriately in the function that the thread runs?
精彩评论