是否可以编写可以在 HPX 和 C++1x 线程之间切换的代码?
Is it possible to write code that can switch between HPX and C++1x thread?
由于 API 在 hpx
和 #include<thread>
之间非常相似,是否可以让相同的代码能够 运行 hpx
或 #include<thread>
?
由于 boost 是 hpx
的要求,我的用例是有些系统不允许 boost,有些是,我希望在两者上使用相同的代码 运行,但尽可能使用 hpx
。
假设我只使用 hpx 和线程中的功能,是否有这样做的示例?我还能通过 #ifdef
吗?
如果两个库的 API 完全相同,您可以使用有条件编译的类型别名:
#if defined(USE_HPX_THREADS)
#include <hpx/thread.hpp>
namespace my_library
{
using my_thread = hpx::thread;
}
#elif defined(USE_STD_THREADS)
#include <thread>
namespace my_library
{
using my_thread = std::thread;
}
#endif
或者,如果 API 不同,您可以创建自己的同类接口,根据预处理器定义使用不同的实现:
class my_thread
{
private:
// "Conditional type alias" like the example above.
my_thread_handle _thread;
public:
void join();
};
#if defined(USE_HPX_THREADS)
void my_thread::join()
{
_thread.hpx_join();
}
#elif defined(USE_STD_THREADS)
void my_thread::join()
{
_thread.std_join();
}
#endif
将不同文件中的实现分开可能是个好主意。查看像 SFML 这样的库 for a real-world example (Unix 和 Win32 文件夹).
std::thread
和 hpx::thread
的 API 完全相同,因此 Vittorio 描述的 using
技巧可以解决问题。
由于 API 在 hpx
和 #include<thread>
之间非常相似,是否可以让相同的代码能够 运行 hpx
或 #include<thread>
?
由于 boost 是 hpx
的要求,我的用例是有些系统不允许 boost,有些是,我希望在两者上使用相同的代码 运行,但尽可能使用 hpx
。
假设我只使用 hpx 和线程中的功能,是否有这样做的示例?我还能通过 #ifdef
吗?
如果两个库的 API 完全相同,您可以使用有条件编译的类型别名:
#if defined(USE_HPX_THREADS)
#include <hpx/thread.hpp>
namespace my_library
{
using my_thread = hpx::thread;
}
#elif defined(USE_STD_THREADS)
#include <thread>
namespace my_library
{
using my_thread = std::thread;
}
#endif
或者,如果 API 不同,您可以创建自己的同类接口,根据预处理器定义使用不同的实现:
class my_thread
{
private:
// "Conditional type alias" like the example above.
my_thread_handle _thread;
public:
void join();
};
#if defined(USE_HPX_THREADS)
void my_thread::join()
{
_thread.hpx_join();
}
#elif defined(USE_STD_THREADS)
void my_thread::join()
{
_thread.std_join();
}
#endif
将不同文件中的实现分开可能是个好主意。查看像 SFML 这样的库 for a real-world example (Unix 和 Win32 文件夹).
std::thread
和 hpx::thread
的 API 完全相同,因此 Vittorio 描述的 using
技巧可以解决问题。