c - 检测操作系统版本并相应地选择线程函数

标签 c windows runtime

是否有一个好的方法来检查操作系统版本(在本例中是否为 Windows Vista+)并在运行时决定将使用哪个版本的函数。

具体来说,我正在谈论在 Win32 线程中实现 pthreads。在我的理想情况下,pthreads 库将在程序启动时确定正在运行哪个操作系统。如果是Vista+,所有函数调用将被重定向到很酷的新的和快速的函数,否则,将使用旧的模拟层。

因此,实际上,该库的每个函数都有两个版本,一个新的一个旧的。一次性运行时检查将在运行时(在程序进入 main 之前)确定将使用哪个版本。我知道有些库可以在运行时检测 SSE 等 CPU 功能,并使用相关函数,但我认为它们会在每个函数调用时进行检查。在我看来,在低级线程库中这样做成本太高。

这可能吗?函数调用可以在运行时“重新链接”/重定向吗?

编辑:像自定义 crt 启动代码这样的疯狂事情是可能的(我说的是 mingw-w64 的 winpthreads,它提供了自己的启动代码)

最佳答案

简单的答案?为您的图书馆定义并构建调度表/结构。像这样的事情:

// Define function pointers and dispatch structure.
typedef void( *PFN_pthread_exit )( void *value_ptr );
typedef struct tag_PTHREAD_IMPL
{
    PFN_pthread_create ptr_pthread_exit;
    // Add the rest rest here.
} PTHREAD_IMPL;

// Define your various implementations dispatcher structures.
static PTHREAD_IMPL legacy_impl = { 
    &legacy_pthread_exit_impl
};
static PTHREAD_IMPL latest_andgreatest_impl = { 
    &pthread_exit_impl
};
static PTHREAD_IMPL* s_pImpl = NULL;

接下来,您的库的初始化函数应包含如下内容:

int StaticInitialize( )
{
    // Initalize dispatcher
    if( latest and greatest OS version )
        s_pImpl = &latest_andgreatest_impl
    else
        s_pImpl = &legacy_impl;
}

最后,您的库导出的函数应如下所示:

int pthread_exit( void *value_ptr )
{
    ASSERT( s_pImpl );
    ASSERT( s_pImpl->ptr_pthread_exit );
    return s_pImpl->ptr_pthread_exit( value_ptr );
}

当然,您需要确保您的现代实现利用运行时绑定(bind)来导出旧平台上不存在的导出。

玩得开心!

关于c - 检测操作系统版本并相应地选择线程函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6333233/

相关文章:

c - N<->1 线程模型如何工作?

windows - Windows 上的 CouchDB?

java - 编译时与运行时错误

python - 在 Windows 上使用内置 python 构建软件安装程序

.net - .NET 运行时是否在内部映射到 win32 函数调用?

c++ - Visual C++ 库 DLL 是否已本地化?

c fOpenThread() 是头文件的这一部分,任何信息

c - 函数声明顺序在 C 语言中很重要,还是我做错了什么?

c - C语言中一个地址减去另一个地址

python - 导入 CV2 : DLL load failed (Python in Windows 64bit)