Click to See Complete Forum and Search --> : Multithreading ... how to synchronize threads?


saaniaferoze
December 25th, 2006, 02:20 AM
I have two threads ... one as a sender and the other a receiver for data sent over sockets. But the sockets are being created and handled in a dll ( a VC# dll which has a class named Class1). so when I call these threads I have to pass the object of the class in the dll because the sender and receiver use the same sockets right!!.

Here is what I have in the sender and receiver threads... ( and I dont know a work around for the DoEvents thing, because I have to enforce the processor to do other tasks while the thread is in a while loop .... and I have removed the doevents completely as well and it doesnt make any difference. So the problem is not with doevents).

DWORD WINAPI SenderThread(LPVOID iValue)

{

Mutex^ mut = gcnew Mutex();

mut->WaitOne();

Class1^ senderdll = *((Class1^*)iValue);

mut->Close();

int returnval;

DoEvents();

while(true)

{

returnval = senderdll->SenderEntryPoint();

if(returnval == 1) // sockets closed

{

break;

//dynamic_cast<AutoResetEvent^>(stateInfo)->Set();

}

}

return 0;

}

DWORD WINAPI ReceiverThread(LPVOID iValue)

{

Mutex^ mut = gcnew Mutex();

mut->WaitOne();

Class1^ receiverdll = *((Class1^*)iValue);

mut->Close ();


int returnval;

DoEvents();

while(true)

{

returnval = receiverdll->ReceiverEntryPoint();

if(returnval == 1) // the sockets closed

break;

}

return 0;

}

and here is how I am creating these threads. (The cmdListen_Click function creates the sockets.)

Class1^ c = gcnew Class1();

c->cmdListen_Click(NewPosition);//call the dll function to create sockets




////Threads start


DWORD dwGenericThread;

hThread2 = CreateThread(NULL,0,SenderThread,&c,0,&dwGenericThread);//the sender thread

if(hThread2 == NULL)

{

DWORD dwError = GetLastError();

return 0;

}

hThread3 = CreateThread(NULL,0,ReceiverThread,&c,0,&dwGenericThread);//the receiver thread

if(hThread3 == NULL)

{

DWORD dwError = GetLastError();

return 0;

}

//////Threads end

Now the two problems I am facing are:

1) How do I synchronize the threads? The AutoResetEvent (as given in http://msdn2.microsoft.com/en-us/library/system.threading.autoresetevent.aspx), uses a threadpool to create threads. My problem is if I use the threadpool instead of using the CreateThread how do I pass the Class1 object in the threads ?

2) My second problem is the AccessViolation error, which I am getting at the point where I create the instance of the Class in the thread. ( in both sender or receiver, depending upon which thread I am creating first !!).

Class1^ receiverdll = *((Class1^*)iValue);

What am I doing wrong here? When I was getting an access violation error in VC#, I used LOCK to enforce resource allocation. How do I do this in VC++?

Marc G
December 26th, 2006, 03:27 PM
[ moved thread ]