Parameter to thread
Hi
I have a secnario where i need two values to be passed to a thread from the point where i begin the thread. i am using the _beginthread api. in that the third parameter is argument list that has to be passed on to a thread. i need to pass two values to the thread.
one way to acheive this is i can convert all the values into a string and pass it as a string. is there any other way to pass more than one value to the thread.
thanks in advance
[478 byte] By [
sspr] at [2007-11-19 20:54:39]

# 1 Re: Parameter to thread
You can create a structure, and then pass a pointer to this structure.
struct yourStruct
{
int a;
int b;
};
// create struct
yourStruct* ptr = new yourStruct;
ptr->a = 5;
ptr->b = 10;
// create thread and pass ptr
_beginthread(... ptr ...);
- petter
# 2 Re: Parameter to thread
#include <stdio.h>
#include <string>
using namespace std;
typedef struct _SOME_PARAMS
{
BYTE anyData[256];
DWORD anyNumber;
} SOME_PARAMS, *LPSOME_PARAMS;
typedef struct _MY_THREAD_PARAMS
{
DWORD myNum;
string myString;
LPSOME_PARAMS myAny;
} MY_THREAD_PARAMS, *LPMY_THREAD_PARAMS;
SOME_PARAMS param1 = { {1, 2, 3, 4}, 0xffffff };
MY_THREAD_PARAMS param0 = {0};
DWORD WINAPI MyThread(LPVOID pVoid)
{
LPMY_THREAD_PARAMS pParam = (LPMY_THREAD_PARAMS)pVoid;
DWORD localNum = pParam->myNum;
string localString = pParam->myString;
LPBYTE localBytes = pParam->myAny->anyData;
// . . . going through
printf("Thread: %s\n", localString.c_str());
return 0;
}
void RunThread()
{
param0.myNum = 10;
param0.myString = "Some string";
param0.myAny = ¶m1;
DWORD threadID;
HANDLE hThread = CreateThread(0, 0, MyThread, (LPVOID)¶m0, 0, &threadID);
// . . .
WaitForSingleObject(hThread, 10000);
}
int main()
{
RunThread();
return 0;
}
# 4 Re: Parameter to thread
If the values only need to be 16-bit you can also use the MAKEWORD() macro to create a 32-bit parameter out of two 16-bit values. Then in the thread function you can use HIWORD() and LOWORD() to separate them again.
philkr at 2007-11-9 14:01:50 >

# 5 Re: Parameter to thread
Here's another method. Make the thread proc a static method of a class and pass the 'this' pointer to _beginthreadex. Then in your thread proc, cast the lpvoid param back into your class pointer and access all the member and methods of the class. Also, put your cleanup/handle closing code into the destructor of the class to make things real tidy.
Arjay at 2007-11-9 14:02:49 >
