如何解决检测操作系统版本并相应地选择线程功能
| 有没有什么好方法可以检查OS版本(在这种情况下是否为Windows Vista +),并在运行时确定要使用的功能版本。 具体来说,我正在谈论在Win32线程中实现pthread。在我的理想情况下,pthreads库将在程序启动时确定运行哪个OS。如果是Vista +,则所有函数调用都将重定向到凉爽的新函数和快速函数,否则,将使用旧的仿真层。 因此实际上,该库将为每个函数提供两个版本,一个是新版本,一个是旧版本。一次运行时检查将确定在运行时,程序进入main之前,可以使用哪个版本。我知道有一些库可以在运行时检测CPU功能(例如SSE)并使用相关功能,但是我认为它们会在每个函数调用时进行检查。在低级线程库IMO中这样做太昂贵了。 这可能吗?可以在运行时“重新链接” /重定向函数调用吗? 编辑:诸如自定义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;
接下来,您的库的initialize函数应包含以下内容:
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 );
}
自然,您需要确保现代实现将运行时绑定用于旧平台上不存在的导出。
玩得开心!