1
votes

native C++ "a.h":

#include <thread>

class a
{
    //... 
private:
    // ...
    std::mutex mutex;
};

C++/CLI:

#include "a.h" // error cause thread is included

my solution:

native C++ "a.h":

class a
{
    a();
    ~a();
    //... 
private:
    // ...
    void* mutex;
};

"a.cpp"

#include <thread>

a::a()
{
    mutex = new std::mutex;
}

~a::a()
{
    delete mutex;
}

C++/CLI:

#include "a.h" // no error
  1. How to do this without dynamic memory allocation?
  2. Is this safe? I somehow use wrapped stuff from < thread > in C++/CLI environment, just not in the header.
  3. Is there a better approach? The new/delete and a cast on every use seems bad. I want to have one mutex per object of the class.
1
when asking for a better solution you need to explain what you want to achieve, not only show your solution. Without dynamic memory allocation? Just use a mutex instead of a mutex*? - 463035818_is_not_a_number
"Just use a mutex instead of a mutex*" Ok. How? - lars
Can you use Standard C++ Libraries in C++/CLI? - Ron
It is formally illegal, you are not allowed to assume that .NET code uses an operating system thread. It depends on the host, it is technically possible that it uses a fiber instead of a thread. That is not actually something to deeply worry about, "green threads" were popular in the previous century and put to pasture by the multi-core revolution. But the rule stands, your mutex isn't going to work at all if it is a fiber. You'll need to hide the implementation detail from the C++/CLI compiler, standard techniques are an abstract interface or the pimpl idiom. - Hans Passant

1 Answers

-1
votes

Templates are here to help you out!

a.h:

template <class MutextType>
class a
{
    //... 
private:
    // ...
    MutextType mutex;
};

And then, in your main or wherever:

#inculde <thread>
//...
a<std::mutex> instance;

And you can also use using statements to clean up if you'd like, for cleaner code:

#inculde <thread>
//...
using MutexA = a<std::mutex>;
//...
MutexA instance;