Access Violation In Multithreaded C Application
I'm trying to write a simple C application that is multithreaded. I want the main thread to be suspended until some flag is set by the worker thread. So for my thread function param I pass a struct that includes the flag. When I assign the flag in the worker thread, I get an access violation. I am using a Mutex to theoretically prevent simultaneous access to this struct instance that is being shared between the main app and the worker thread. Can someone point me in the right direction? The full project code is below. I have denoted the error line in comments in the THREADFUNCS.C file.
GLOBALS.H
#ifndef _globals_h
#define _globals_h
#include <windows.h>
static HANDLE ghMutex;
#endif
THREADCOM.H
#ifndef _threadcom_h
#define _threadcom_h
typedef struct {
char bContinueMain;
} RComData;
#endif
THREADFUNCS.H
#ifndef _threadfuncs_h
#define _threadfuncs_h
#include <windows.h>
extern DWORD WINAPI ThreadA(LPVOID params);
#endif
THREADFUNCS.C
#include <stdio.h>
#include "threadcom.h"
#include "threadfuncs.h"
#include "globals.h"
DWORD WINAPI ThreadA(LPVOID params)
{
RComData* pr = (RComData*)params;
int i;
printf("You are in thread A.\n");
WaitForSingleObject(ghMutex, INFINITE);
pr->bContinueMain = TRUE; /* ACCESS VIOLATION HERE */
ReleaseMutex(ghMutex);
for (i=0; i<10; ++i)
{
printf("Printing THREAD A line %i.\n", i);
}
}
MAIN.C
#include <windows.h>
#include <stdio.h>
#include "threadfuncs.h"
#include "threadcom.h"
#include "globals.h"
void WaitForGoAhead(RComData* pr)
{
char bGo = FALSE;
while (!bGo)
{
WaitForSingleObject(ghMutex, INFINITE);
if (pr->bContinueMain)
bGo = TRUE;
ReleaseMutex(ghMutex);
}
}
int main(void)
{
int i;
HANDLE hThreadId = -1;
RComData r = { FALSE };
hThreadId = CreateThread(0, 0, ThreadA, 0, &r, &hThreadId);
WaitForSingleObject(hThreadId, 1);
if (hThreadId > 0)
{
printf("Thread has been laun开发者_开发知识库ched.\n");
ghMutex = CreateMutex(0, FALSE, 0);
WaitForGoAhead(&r);
for (i=0; i<10; ++i)
{
printf("Printing main proc line %i.\n", i);
}
WaitForSingleObject(hThreadId, INFINITE);
printf("Thread is complete.\n");
CloseHandle(ghMutex);
CloseHandle(hThreadId);
}
else
{
printf("Thread failed to created.\n");
}
printf("Press any key to exit...");
getchar();
return 0;
}
Thank you.
You need to create the mutex before you create the thread.
Right now your thread will WaitForSingleObject on an invalid handle
The parameter &r
should be the 4th parameter in the CreateThread call. It is currently 0 (null), which would cause an access violation when you dereference the pointer in the thread function.
You have multiple static variables called ghMutex (one in main.c, one in threadfuncs.c). You should combine these into a single mutex, then initialise it before you create the new thread.
in globals.h:
extern HANDLE ghMutex;
in main.c:
HANDLE ghMutex = 0;
In main.c move the mutex initialisation before the thread is created.
精彩评论