我會強烈建議不要鑄造函數指針void *
指針,在C++中也可能有C爲好,大小可能會有所不同。
總的來說,你的解決方案不是非常的C++。無可否認,使用c庫會使它有點棘手。下面是我用我的當前項目的方法: -
class ThreadBase
{
public:
ThreadBase()
{
}
virtual ~ThreadBase()
{
// TODO - inform thread to stop, using a message or a signal or something
// and then wait for the thread to terminate
void
*return_value = 0;
pthread_join (m_thread_handle, &return_value);
}
void Run()
{
if (pthread_create (&m_thread_handle, 0, ThreadFunction, this))
{
// error - throw an exception or something
}
}
private:
static void *ThreadFunction (void *param)
{
ThreadBase
*thread = static_cast <ThreadBase *> (param);
thread->Main();
return 0;
}
virtual void Main() = 0;
private:
pthread_t
m_thread_handle;
};
,然後從ThreadBase實施特定版本獲得:
class SomeThread : public ThreadBase
{
private:
void Main()
{
// do something
}
};
你可能想改變Main
返回的退出代碼,並通過那從線程回來。如果它處於無限循環(例如,如果它是一個偵聽器,消費某種類型的消息),則需要一種方法使Main
退出。
我編輯了你的標題。請參閱[「應該在其標題中包含」標籤「?」](http://meta.stackexchange.com/questions/19190/),其中的共識是「不,他們不應該」。 – Default
是運行一個靜態方法嗎?如果沒有,你不能像那樣使用它。實例方法隱含地與實例('* this'指針)相關聯 –
您可以使用正確的簽名創建一個非成員函數,然後通過它。 –