Note that there are some explanatory texts on larger screens.

plurals
  1. POAccess Violation In Multithreaded C Application
    text
    copied!<p>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.</p> <p>GLOBALS.H</p> <pre><code>#ifndef _globals_h #define _globals_h #include &lt;windows.h&gt; static HANDLE ghMutex; #endif </code></pre> <p>THREADCOM.H</p> <pre><code>#ifndef _threadcom_h #define _threadcom_h typedef struct { char bContinueMain; } RComData; #endif </code></pre> <p>THREADFUNCS.H</p> <pre><code>#ifndef _threadfuncs_h #define _threadfuncs_h #include &lt;windows.h&gt; extern DWORD WINAPI ThreadA(LPVOID params); #endif </code></pre> <p>THREADFUNCS.C</p> <pre><code>#include &lt;stdio.h&gt; #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-&gt;bContinueMain = TRUE; /* ACCESS VIOLATION HERE */ ReleaseMutex(ghMutex); for (i=0; i&lt;10; ++i) { printf("Printing THREAD A line %i.\n", i); } } </code></pre> <p>MAIN.C</p> <pre><code>#include &lt;windows.h&gt; #include &lt;stdio.h&gt; #include "threadfuncs.h" #include "threadcom.h" #include "globals.h" void WaitForGoAhead(RComData* pr) { char bGo = FALSE; while (!bGo) { WaitForSingleObject(ghMutex, INFINITE); if (pr-&gt;bContinueMain) bGo = TRUE; ReleaseMutex(ghMutex); } } int main(void) { int i; HANDLE hThreadId = -1; RComData r = { FALSE }; hThreadId = CreateThread(0, 0, ThreadA, 0, &amp;r, &amp;hThreadId); WaitForSingleObject(hThreadId, 1); if (hThreadId &gt; 0) { printf("Thread has been launched.\n"); ghMutex = CreateMutex(0, FALSE, 0); WaitForGoAhead(&amp;r); for (i=0; i&lt;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; } </code></pre> <p>Thank you.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload