Reputation: 897
In my app two threads invoke the same recursive function, that should output data to some file. I don't know how I can synchonized this threads to output correct data. I try a few variants with mutex (commented in code using /** n **/), but it doesn't work (output data are mixed from different threads). How can I organize synchronizathion(i should use only WinAPI and std). Pseudocode below:
HANDLE hMutex = CreateMutex(NULL,FALSE, 0);
wchar_t** HelpFunction(wchar_t const* p, int *t)
{
do
{
/**** 1 ****/ //WaitForSingleObject(hMutex, INFINITE);
wchar_t* otherP= someFunction();
if(...)
{
/**** 2 ****/ //WaitForSingleObject(hMutex, INFINITE);
//File's output should be here
//Outputing p
/**** 2 ****/ //ReleaseMutex(hMutex);
}
if(...)
{
HelpFunction(otherP, t);
}
/**** 1 ****/ //ReleaseMutex(hMutex);
}while(...);
}
unsigned int WINAPI ThreadFunction( void* p)
{
int t = 0;
/**** 3 ****/ //WaitForSingleObject(hMutex, INFINITE);
wchar_t** res = HelpFunction((wchar_t *)p, &t);
/**** 3 ****/ //ReleaseMutex(hMutex);
return 0;
}
void _tmain()
{
HANDLE hThreads[2];
hThreads[0] = (HANDLE)_beginthreadex(NULL, 0, ThreadFunction, L"param1", 0, NULL);
hThreads[1] = (HANDLE)_beginthreadex(NULL, 0, ThreadFunction, L"param2", 0, NULL);
WaitForMultipleObjects(2, hThreads, TRUE, INFINITE);
}
Upvotes: 1
Views: 395
Reputation: 31445
With Windows API, if it is a single process, you are probably better off using a Critical Section.
There is no need for a WaitForSingleObject on the critical section, you only use that when you are waiting for some data to write if that is going to happen.
And what I guess you are synchronising is the file-write so each thread writes one whole record at a time. (Ensure you flush any buffers).
You will call
EnterCriticalSection
when you get to the sensitive part and
LeaveCriticalSection
at the end of the sensitive part.
and look here for the more details API.
The recursion doesn't matter here as long as you are not holding the "lock" at the point you recurse, i.e. you do not recurse from within your critical section code. When you recurse as with the code shown, it will NOT spawn a new thread. I don't know if you were expecting it to.
I cannot actually see any file I/O in your HelpFunction. I do however see the pointer that you just called t. It is the same pointer for both threads and it is non-const. Therefore if both threads are going to be writing to that int, you may need to synchronise that too. Once again your code does not actually show how that pointer is being used.
Upvotes: 1