2013-02-04 49 views
0

我有一个想法如何使非常简单的跨平台(Linux/Windows)的线程功能。这是我的示例代码:克隆C++数据类型为多平台的目的

#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 

恐怕首先会看起来像veird的问题,但继续记住,我初学者,我需要了解C++。随意编辑那些我离开的部分“我不知道”评论。
如果您认为这是错误的问题,请留下评论,我应该如何问。

+4

['std :: thread'](http://en.cppreference.com/w/cpp/thread)是否适用于所有环境? –

+0

哇,那标准::看起来像治愈一切。每次我寻求多平台时,都会有人用std :: function显示出来。非常感谢你。但我仍然对如何做这个跨平台的东西感兴趣。 –

+1

如果你好奇或者你的环境还没有C++ 11,你可以看看Boost,它包含一个线程包装类,它被移植到许多不同的操作系统中。 –

回答

1
  1. 开始具有像Thread.h平台无关的头,将抽象的所有线程函数
  2. 有在* $ platform.cpp文件平台相关的代码
  3. 显然构建系统应该只编译平台相关代码

现在,对于特定代码

使用这样的定义泛型类型

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(..) 读取特定IMPL

的文档回调,你可以使用类似

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); 
+0

似乎'typedef'是我正在寻找。使用多个我们的好点 - 当然,我需要更多的多平台功能。 –