Click to See Complete Forum and Search --> : Accessing struct members in side a thread


redspider
October 3rd, 2005, 05:49 AM
What im trying todo is access struct members inside a thread and use the same struct for every thread, the code here compiles fine but when it runs i get a popup saying the memory cannot be found bla bla bla , What am i doing rong ?

The output i want is - 1234


#define X_THREADS 4
typedef struct ThrStc
{
int Anumber;

} ThrStc;

DWORD WINAPI ThreadX(LPVOID param)
{
ThrStc *ps = (ThrStc *)param;
ps->Anumber++;
printf("%d", ps->Anumber);

return 0;
}

int main(void)
{
HANDLE hThread[X_THREADS];
DWORD dwID[X_THREADS];
DWORD dwRetVal = 0;

ThrStc StcNme;
StcNme.Anumber = 0;

for(int i=0; i<X_THREADS; i++ )
{
hThread[i] = CreateThread(NULL, 0, &ThreadX, 0, 0, &dwID[i]);
}

dwRetVal = WaitForMultipleObjects(X_THREADS, hThread, TRUE, INFINITE);

for(i=0; i<X_THREADS; i++)
{
CloseHandle(hThread[i]);
}

return 0;
}

Arjay
October 3rd, 2005, 11:51 AM
You need to pass in the structure as the forth param of CreateThread.

hThread[i] = CreateThread(NULL, 0, &ThreadX, &StcNme, 0, &dwID[i]);

One thing to be aware of is that you are sharing the structure between multiple threads and anytime you share a resource between threads, you must synchronize access to the resource. If you don't, it may lead to memory corruption.

Of course, in this simple example, you probably won't experience memory corruption with a memory type of int, but if you changed the member of the structure to a string, you would most certainly see corruption.

For a quick primer on sharing resources between threads, check out the following two CG articles:

Win32 Thread Synchronization, Part 1: Overview (http://redir.internet.com/!search/www.codeguru.com/Cpp/W-D/dislog/win32/article.php/c9823)

Win32 Thread Synchronization, Part 2: Helper Classes (http://redir.internet.com/!search/www.codeguru.com/Cpp/misc/misc/threadsprocesses/article.php/c9825)

These articles discuss issues regarding sharing resources between threads, common pitfalls, and offer a set of classes to safely share resources.

Arjay