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

标签 c multithreading winapi mutex access-violation

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

全局.H

#ifndef _globals_h
#define _globals_h

#include <windows.h>


static HANDLE ghMutex;


#endif

线程通信.H

#ifndef _threadcom_h
#define _threadcom_h

typedef struct { 
   char bContinueMain;
} RComData;

#endif

线程函数.H

#ifndef _threadfuncs_h
#define _threadfuncs_h 

#include <windows.h>

extern DWORD WINAPI ThreadA(LPVOID params);

#endif

线程函数.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);
   }
}

主程序

#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;
}

谢谢。

最佳答案

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

现在您的线程将在无效句柄上 WaitForSingleObject

关于c - 多线程 C 应用程序中的访问冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5080034/

相关文章:

C++:如何将多个对象复制到剪贴板并在之后提取它们?

c++ - 检测内存泄漏的工具

c - 是否可以通过 getopt_long 参数列表向后移动?

java - 如何在Java中使用单独的线程调用方法?

multithreading - 从 Perl 线程运行 bash 脚本

c - 更新标题栏 Winapi

delphi - 如何临时加载字体?

无论用户输入如何,将输入转换为 int

C - 使用带 ** 参数的函数释放结构的已分配内存

python - 使用 py2app 构建 PySide 应用程序包时,QApplication 未在主线程中运行