2010-12-10 25 views
0

這是我在論壇上的第一篇文章,但我不太確定我是否在問正確的地方? - 我可以在本節發佈C++問題嗎?或者這就像一般的編程部分?無論如何,足夠的我沒有什麼疑惑,讓我們來解決我的問題:)。 在我的.h文件(thread.h)中,我有一個struct(RUNNABLE)和一個類(線程)。 'RUNNABLE'就像你實現和覆蓋的接口,或者至少你覆蓋它的虛擬'run()'void。然後創建一個'線程'實例並調用其'start(void * ptr)'函數來啓動線程。你傳入一個具有RUNNABLE作爲基類的對象實例作爲'start'函數的參數。 這一切似乎很好,但我的實現崩潰我的程序。 這裏的thread.h:使用我的線程實現時程序失敗?

#include <process.h> 

struct RUNNABLE{ 
    virtual void run() = 0; 
}; 

class thread{ 
public: 
    void start(void *ptr){ 
     DWORD thr_id; 
     HANDLE thr_handl = (HANDLE)_beginthreadex(NULL, 0, thread_proc, ptr, 0, (unsigned int*)&thr_id); 
    } 
private: 
    static unsigned int __stdcall thread_proc(void *param){ 
     ((RUNNABLE*)param)->run(); 
     ExitThread(0); 
     return 0; 
    } 
}; 

這是我的示例實現:

class test : RUNNABLE{ 
    virtual void run(){ 
     while(true){ 
      dbText(0, 0, "hej"); 
     } 
    } 
}; 

test *obj = new test(); 
thread th; 
th.start(obj); 

和程序,當我打開它只是簡單地崩潰。 幫助表示讚賞:)。

此致敬禮, 本傑明。

+2

你是在正確的地方...歡迎來到StackOverflow! – 2010-12-10 22:30:53

+0

您收到錯誤訊息? – 2010-12-10 22:41:46

+1

如果你使用_beginthreadex() – jmucchiello 2010-12-10 22:54:49

回答

0

我測試了它,它運行的很好,可能是你的dbText thingy那裏崩潰了,我用printf(「hejdå」)取代了它。

0

這將運行對我罰款:

#include <iostream> 
#include <process.h> 
#include <windows.h> 

struct RUNNABLE{ 
    virtual void run() = 0; 
}; 

class thread{ 
public: 
    void start(void *ptr){ 
     DWORD thr_id; 
     HANDLE thr_handl = (HANDLE)_beginthreadex(NULL, 0, thread_proc, ptr, 
                0, (unsigned int*)&thr_id); 
    } 
private: 
    static unsigned int __stdcall thread_proc(void *param){ 
     ((RUNNABLE*)param)->run(); 
     std::cout << "ending thread\n"; 
     ::ExitThread(0); 
     return 0; 
    } 
}; 

class test : RUNNABLE{ 
    virtual void run(){ 
     for(unsigned int u=0; u<10; ++u){ 
      std::cout << "thread\n"; 
     } 
    } 
}; 


int main() 
{ 
    test *obj = new test(); 
    thread th; 
    th.start(obj); 

    std::cout << "giving thread some time\n"; 
    ::Sleep(5000); 
    std::cout << "ending process\n"; 

    return 0; 
} 

但是,你應該叫_endthreadex()(而不是EndThread())結束線程。

1

test * obj = new test();

這是一個內存管理問題。 obj何時被刪除?該線程可能需要一段時間才能真正開始運行,該對象需要保持足夠長的時間。我猜你已經有一些代碼不在刪除該對象的代碼片段中了。太快了。

唯一可以安全,準確地刪除對象的代碼就是線程本身。