Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround for mutex in native lib for CLI DLL

I am writing a C++/CLI wrapper for a native C++ library. In one of the classes that is returned back to the CLI wrapper, uses thread and, specifically #include <mutex> in the header to define the class level mutex.

The problem is once the header is brought into the CLI code (with the /clr option enabled), I get the error that <mutex> is not supported when compiling with /clr or /clr:pure.

Reading this post How to implement a unmanaged thread-safe collection when I get this error: <mutex> is not supported when compiling with /clr, there was a blog article which mentions some possible work arounds. The workarounds, however, assume that you don't need any header files which cause a conflict and all can be done within the class functions, essentially hiding the thread functions from the CLI app.

In the case of a class level mutex, this is not the case. It has to be in the header.

Is there any way to make a CLI app work with a native lib that is threaded?

Yes, I am aware of the GetCurrentThreadID() issue between managed and unmanaged code, but what is the right approach? Or is there no way around it?

I cringe at having to incorporate something like ZMQ because this is in a critical section and now having three copies of data (which could be very large) would be prohibitive. (one on the managed side, one on the native, and one to pass through the message buffer in ZMQ). I am aware of ZMQ's zero copy, but have not tried inproc between managed and unmanaged c++ to see if it is possible to share memory. If it is possible, it would probably require a low level contiguous data structure to be used throughout the application or suffer the consequences of copying the data again.

Any wizards out there with a decent solution?

like image 714
user3072517 Avatar asked Nov 09 '22 19:11

user3072517


1 Answers

The solution is to use #ifdef to selectively hide the declaration of the mutex in the .h file in CLI code but still compile it in the cpp native code.

nativeClass.h file:

#ifdef NATIVE_CODE
    #include <mutex>
#endif

class naticeClass {
public:
    void doSomething();
private:
#ifdef NATIVE_CODE
    mutex _mutex;
#endif

};

in nativeClass.cpp:

#define NATIVE_CODE 
#include "nativeClass.h"

void nativeClass:doSomething()
{
    _mutex.lock();
    ...

}
like image 117
AlexP Avatar answered Nov 15 '22 08:11

AlexP