我有一个想法如何使非常简单的跨平台(linux / windows)线程功能。这是我的示例代码:
#if LINUX
#include <pthread.h>
ThreadHandle createThread(???* callback, void* data) { //I dont know what is data type of function pointer, sorry
pthread_t handle;
pthread_create(&handle, 0, callback, (void*)data);
return (ThreadHandle)handle;
}
define_data_type ThreadHandle = pthread_t; //I don't know how this is done at all, sorry
#endif
#if WINDOWS
#include <windows.h>
ThreadHandle createThread(???* callback, void* data) {
HANDLE handle = CreateThread(
NULL, // default security attributes
0, // use default stack size
callback, // thread function name
data, // argument to thread function
0, // use default creation flags
NULL); // returns the thread identifier - I don't need this, do I?
}
define_data_type ThreadHandle = HANDLE; //I don't know how this is done at all, sorry
#endif
恐怕这首先看起来像是一个棘手的问题,但是请记住我是新手,并且我需要了解C ++。随时编辑我留下“我不知道”评论的那些部分。
如果您认为这是一个错误的问题,请留下评论我应该怎么问。
最佳答案
首先拥有一个独立于平台的标头,例如Thread.h,它将抽象所有线程功能
在*。$ platform.cpp文件中具有平台特定的代码
显然,您的构建系统应仅编译平台相关的代码
现在,针对特定代码
使用这样的东西来定义泛型
typedef unsigned long os_error_t;
typedef void * os_console_handle;
typedef void * os_thread_handle;
typedef void * os_event_handle;
typedef unsigned long os_pid_t;
typedef unsigned long os_thread_id;
在Linux上,使用并调用pthread_create(..)
在Windows上,使用并调用CreateThread(..)
阅读文档以获取特定的印象
对于回调,您可以使用类似
typedef os_error_t (*thread_start_function_t)(void *);
class InternalThreadArgs {
thread_start_function_t m_func;
void *m_pArg;
public:
InternalThreadArgs(thread_start_function_t pf, void *pArg) {
m_func = pf;
m_pArg = pArg;
}
os_error_t Run() {
return m_func(m_pArg);
}
};
现在,
具有您的抽象方法签名,例如
os_error_t create_thread(thread_start_function_t pf, void *pArg, os_thread_handle *pHandle);