Click to See Complete Forum and Search --> : How to pass a variable in a worker thraed to other worker threads?
Apal
July 23rd, 2005, 09:48 PM
I want to pass the parameter- variable "i" in a worker thread to five other worker threads because I need to used "i" in other worker threads.
I found in MSDN "CreateThread(NULL, 0, Function, "pointer to a variable passed to thread", 0, &dwID)". But I really don't know How to achieve this?
Here is my code:
UINT CTestDlg::Thread(LPVOID pParam)
{
HANDLE hThreads [5];
DWORD dwID;
for(int i =0; i < 5; i++)
{
hThreads[i] = CreateThread(NULL, 0, Function, ???, 0, &dwID);
}
return 0;
}
DWORD WINAPI CTestDlg::Function(LPVOID pParam)
{
//how to get i here????
if(i ==0)
{
.....;
.....
}
if(i == 1)
{
....;
.....;
}
........................;
return 0;
}
Thanks a lot.
golanshahar
July 24th, 2005, 12:08 PM
here is a sample of passing paramter to the Theard via ::CreateTheard(..)
please note that since passing a poiner as a variable, you should be aware not to pass an automatic variable. in my sample below i decalre it static just so you will see how it should work.
DWORD WINAPI Function(LPVOID pParam)
{
int i = *((int*)pParam);
// i = 1234
return 0;
}
void CMyDlg::OnOK()
{
DWORD dwID;
static int i=1234;
HANDLE handle = ::CreateThread(NULL, 0, Function,&i, 0, &dwID);
}
Cheers
Apal
July 24th, 2005, 12:37 PM
Thanks a lot.
This is excatly what I want and really solves the problem.
Arjay
July 24th, 2005, 03:52 PM
Since you are coding in C++, you may want to pass in a reference to the whole class. That way you have access to all the variables and don't need to create another object such as a structure when you want to pass more than one variable.
To do this, during thread creation, you pass in the *this* ptr.
= CreateThread(NULL, 0, Function, this, 0, &dwID);
Make the thread proc static and use the LPVOID param to
retrieve the class instance.
static DWORD WINAPI CTestDlg::Function(LPVOID pParam)
{
CTestDlg pTestDlg = static_cast<CTestDlg*>( pParam );
// etc.
}
Note: since you are using the Win32 CreateThread (as opposed to the MFC CWinThread::CreateThread), you need to be sure the close the thread handle with ::CloseHandle().
Arjay
NMTop40
July 25th, 2005, 07:32 AM
But what use is that? He wants each thread to have its own 'i'.
You could create a struct for each thread thus:
struct ThreadData
{
CTestDlg * pDlg;
int i;
ThreadData( CTestDlg * pDlg0, int i0 )
: pDlg( pDlg0 ), i( i0 )
{
}
};
Now pass to each one:
CreateThread( NULL, 0, Function, new ThreadData( this, i ), 0, &dwID );
On entering the CreateThread function you must cast the pointer to a ThreadData * and on exiting you must delete it (to match the "new").
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.