且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

跨标准实现工作的互斥体

更新时间:2023-11-13 22:49:52

从主可执行文件(mingw-w64)导出到DLL(VC ++)-使用单独的编译器进行编译-同步/互斥对象句柄"(不透明的指针) ,通常,尽管它也可以是某些内容的索引)和一对C样式的函数(如果需要,您可以将它们包装到std::mutexstd::lock这样的类中,以暴露相同的API-最安全的操作)锁定并解锁该手柄.它们可能就这样裸露,或者它们可能包含超时或尝试锁定之类的其他功能-这些功能非常有用,但不是必需的.您还可以导出handle_t create()void delete(handle_t handle)函数.

Export from your main executable (mingw-w64) to your DLL (VC++) - compiled with separate compilers - a synchronization/mutex "handle" (an opaque pointer, typically, though it can be an index into something too) and a pair of C-style functions (if you want, you can wrap them into classes like std::mutex and std::lock, exposing the same API - that'd be the safest thing to do) lock and unlock that take that handle. They can be just as bare as that, or they might include additional functionality like timeout, or try-lock - these are quite useful but not required. You can also export handle_t create() and void delete(handle_t handle) functions.

重点是,同步对象本身(互斥体或其他对象)始终由那些间接函数操纵以避免使用错误,并且这些函数取决于编译器(可以容易地由预处理器检测到),由特定于编译器的原子操作内部函数或CRT函数提供支持,例如完美匹配的 InterlockedCompareExchange (它也适用于mingw-w64)及其特定于Visual C ++的 __atomic (更具体地说是__atomic_compare_exchange).

The point is that the sync object itself (the mutex or whatever) is always manipulated by those indirection functions to avoid errors in usage, and these functions are, depending on the compiler (that can easily be detected by the preprocessor), backed by compiler-specific atomic operation intrinsics or CRT functions, like the perfectly fitting InterlockedCompareExchange (it works under mingw-w64 too) and its Visual C++ specific compiler intrinsic variant, or GCC's __atomic (more specifically, __atomic_compare_exchange).