I gave this a try on this very simple example. From what I can tell, the mutex version might even be slightly faster. Did I implement this right and is this too simple of an example to really test this out on?
Code:
#include <windows.h>#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#ifdef MUTEX_FLAG
HANDLE ghMutex;
#else
bool flag[2] = { false, false };
int turn;
#endif
DWORD WINAPI ThreadRoutine1(LPVOID lpArg)
{
int i = 0;
while (i<100)
{
#ifdef MUTEX_FLAG
WaitForSingleObject(
ghMutex, // handle to mutex
INFINITE); // no time-out interval
#else
flag[0] = true;
turn = 1;
while (flag[1] && turn == 1)
{
#ifdef LOOP_DELAY
Sleep(1);
#endif
}
#endif // MUTEX_FLAG
// critical section
printf("Thread1 i = %d\n", --*(int *)lpArg);
// end of critical section
#ifdef MUTEX_FLAG
ReleaseMutex(ghMutex);
#else
flag[0] = false;
#endif
i++;
}
return NULL;
}
DWORD WINAPI ThreadRoutine2(LPVOID lpArg)
{
int i = 0;
while (i<100)
{
#ifdef MUTEX_FLAG
WaitForSingleObject(
ghMutex, // handle to mutex
INFINITE); // no time-out interval
#else
flag[1] = true;
turn = 0;
while (flag[0] && turn == 0)
{
#ifdef LOOP_DELAY
Sleep(1);
#endif
}
#endif
// critical section
printf("Thread2 i = %d\n", ++*(int *)lpArg);
// end of critical section
#ifdef MUTEX_FLAG
ReleaseMutex(ghMutex);
#else
flag[1] = false;
#endif
i++;
}
return NULL;
}
int main()
{
int lpArgPtr;
HANDLE hHandles[2];
DWORD ThreadId;
clock_t t0;
t0 = clock();
lpArgPtr = 10;
#ifdef MUTEX_FLAG
ghMutex = CreateMutex(
NULL, // default security attributes
FALSE, // initially not owned
NULL); // unnamed mutex
if (ghMutex == NULL)
{
printf("CreateMutex error: %d\n", GetLastError());
return 1;
}
#endif
hHandles[0] = CreateThread(NULL, 0, ThreadRoutine1, &lpArgPtr, 0, &ThreadId);
if (hHandles[0] == NULL) {
fprintf(stderr, "Could not create Thread\n");
exit(0);
}
else
printf("Thread %d was created\n", ThreadId);
hHandles[1] = CreateThread(NULL, 0, ThreadRoutine2, &lpArgPtr, 0, &ThreadId);
if (hHandles[1] == NULL) {
fprintf(stderr, "Could not create Thread\n");
exit(0);
}
else
printf("Thread %d was created\n", ThreadId);
for (int i = 0; i < 2; i++)
{
WaitForSingleObject(hHandles[i], INFINITE);
}
#ifdef MUTEX_FLAG
CloseHandle(ghMutex);
#endif
printf("program runtime %.4f\n", 1.0 * (clock() - t0) / CLOCKS_PER_SEC);
system("Pause");
return 0;
}