Click to See Complete Forum and Search --> : Parameter to thread


sspr
April 19th, 2006, 04:53 AM
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

wildfrog
April 19th, 2006, 05:05 AM
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

Igor Vartanov
April 19th, 2006, 05:16 AM
#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 = &param1;

DWORD threadID;
HANDLE hThread = CreateThread(0, 0, MyThread, (LPVOID)&param0, 0, &threadID);
// . . .
WaitForSingleObject(hThread, 10000);
}


int main()
{
RunThread();
return 0;
}

Marc G
April 19th, 2006, 01:50 PM
[ moved thread ]

philkr
April 19th, 2006, 02:08 PM
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.

Arjay
April 19th, 2006, 08:55 PM
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.