<thread> 在 C++/CLI 代码中包含的代码中使用。寻找更好的解决方案

Using <thread> in code which is included in C++/CLI code. Looking for a better solution

本文关键字:代码 寻找 解决方案 更好 lt 包含 C++ CLI thread gt      更新时间:2023-10-16

native C++ "a.h":

#include <thread>
class a
{
    //... 
private:
    // ...
    std::mutex mutex;
};

C++/命令行界面:

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

我的解决方案:

母语C++"A.H":

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

"阿.cpp"

#include <thread>
a::a()
{
    mutex = new std::mutex;
}
~a::a()
{
    delete mutex;
}

C++/命令行界面:

#include "a.h" // no error
  1. 如何在没有动态内存分配的情况下执行此操作?
  2. 这安全吗?我不知何故在 C++/CLI 环境中使用来自<线程>的包装内容,只是不在标头中。
  3. 有没有更好的方法?每次使用的新/删除和强制转换似乎很糟糕。我想每个类的对象都有一个互斥锁。

模板在这里为您提供帮助!

啊:

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

然后,在您的主要或任何地方:

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

如果需要,您还可以使用 using 语句进行清理,以获得更干净的代码:

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