我不知道CreateThread()
,但看起來像一個C風格的界面來創建線程:你可能不能夠通過一個函數對象。最有可能的啓動功能類型是
extern "C" typedef void (*entry_funciont)(void*);
道德等同可能與一些額外的參數和返回的東西比void
不同。你需要一個轉發函數來恢復你的函數對象,你需要知道傳遞給CreateThread()
函數的函數對象的確切類型,作爲「用戶數據」(我猜你在哪裏通過NULL
。函數對象你可以使用沿此線的東西:
struct entry_base {
virtual ~entry_base() {}
virtual void call() = 0;
};
template <typename Fun>
struct entry
: entry_base {
Fun fun;
entry(Fun fun): d_fun(fun) {}
void call() {
this->d_fun();
delete this;
}
};
template <typename Fun>
entry_base* make_entry(Fun fun) {
return new entry<Fun>(fun);
}
extern "C" void call_entry(void* entry) {
static_cast<entry_base*>(entry)->call();
}
...然後可以使用這樣的事情:
base* b = ...; // you can't use a local object here!
handle = CreateThread(NULL, 0,
LPTHREAD_START_ROUTINE(&call_entry),
make_entry(bind2nd(mem_fun_ref(&base::show), &b)),
NULL, &dword);
請注意,我有些猜測的接口CreateThread()
,即用戶數據指針可能會進入不同的位置,但是,綁定到一個指針ter本地對象幾乎肯定不會起作用:在線程運行時,該對象可能會超出範圍,並且會刪除該對象運行的基礎。
的兩個答案你都是對的,但要注意,你通常應該使用'_beginthreadex()'而不是'的CreateThread()',否則對於新線程,CRT可能無法正確初始化。 –