user758114
user758114

Reputation: 354

Mutex sharing between DLL and application

I have an multithreaded application that uses a DLL that I created. There is a certain function that will fail if the DLL has not run a certain function yet. How can I make sure that the thread that runs this application function waits for that DLL function to complete before continuing?

Visualization:

O = DLL Function Completes

T = Application Function Starts

App Thread:--------------O----------------------------------

DLL Thread:----------------------T--------------------------

Upvotes: 1

Views: 978

Answers (2)

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17415

Several approaches:

  • First thought would be to put the code into DLLMain(), which is executed automatically on application/DLL load. Not everything can be done here though, like blocking operations or operations that require loading other DLLs. Be sure to read and understand the docs if you try this approach.
  • The second thought is to throw or assert(), so that the init function must be called before any other one, like WSAStartup(). You would then have to call this once in main() before creating any other threads. This is a simple approach. It requires manual work and you can't create threads inside the ctors of globals (which is always dangerous anyway), but at least it will tell you if you got it wrong and, assuming the assert() approach, has zero overhead for release builds.
  • A third variant is using Boost.Thread's One-time Initialization initialization, which seems to do what you want.

Upvotes: 3

Panda
Panda

Reputation: 1239

You could use a named event.

Create an event for both the app and DLL to share first:

HANDLE myEvent = CreateEvent(NULL, false, false, L"MyEvent");

To signal complete use:

SetEvent(myEvent);

To wait for completion use:

WaitForSingleObject(myEvent, INFINITE);

Upvotes: 1

Related Questions