多线程C应用程序中的访问冲突

时间:2011-02-22 15:21:07

标签: c multithreading winapi mutex access-violation

我正在尝试编写一个多线程的简单C应用程序。我希望主线程被挂起,直到工作线程设置了一些标志。所以对于我的线程函数参数,我传递一个包含该标志的结构。当我在工作线程中分配标志时,我得到访问冲突。我正在使用Mutex理论上阻止同时访问主应用程序和工作线程之间共享的此结构实例。有人能指出我正确的方向吗?完整的项目代码如下。我在THREADFUNCS.C文件的注释中表示了错误行。

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 launched.\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;
}

谢谢。

3 个答案:

答案 0 :(得分:6)

您需要在创建线程之前创建互斥锁

现在你的线程将WaitForSingleObject放在无效句柄

答案 1 :(得分:3)

参数&r应该是CreateThread调用中的第4个参数。它当前为0(null),当您取消引用线程函数中的指针时会导致访问冲突。

答案 2 :(得分:1)

你有多个名为ghMutex的静态变量(一个在main.c中,一个在threadfuncs.c中)。您应该将它们组合到一个互斥锁中,然后在创建新线程之前将其初始化。

在globals.h中

extern HANDLE ghMutex;

在main.c中:

HANDLE ghMutex = 0;

在main.c中,在创建线程之前移动互斥锁初始化。