2011-04-03 113 views
2

我在我的程序中使用了方法'pthread_create',並在此方法中出現了分段錯誤。
什麼可能導致這種情況?我用正確的參數類型調用這個函數!pthread_create分段錯誤

這是代碼:

pthread_t* _daemon; 


void* writer(void* arg){ 
    // stuff that dont involve "arg"... 
} 


int initdevice(){ 
    if(pthread_create(_daemon, NULL, &writer, NULL) != 0) //seg in this line 
    { 

     cerr << "system error\n"; 
     return ERR_CODE; 
    } 
    return SUCCESS; 
} 

int main() { 
    initdevice(); 
    return 0; 
} 

注:我試圖調用到作家在pthread_create之前也運行它沒有「&」,也是 - 我們嘗試發送給該方法一些void *參數而不是最後一個NULL參數。

+4

發佈你在這個調用中使用的代碼,你可能做得不對。 – Mat 2011-04-03 16:53:45

+0

我認爲問題出在第17行。 – Nawaz 2011-04-03 16:55:09

+1

不要使用下劃線'_'作爲全局變量的第一個字符(只是不要在變量的開頭使用它們)。 [這些標識符保留給編譯器和操作系統](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-ac-identifier/228797#228797 )。 – 2011-04-03 17:22:47

回答

13

你probelem是在這裏:

pthread_t* _daemon; 

這應該是:

pthread_t daemon; 

然後改變調用在pthread_create:

if(pthread_create(&daemon, NULL, &writer, NULL) != 0) 

的想法是,在pthread_create需要一個指針一個現有的 pthread_t對象,以便它可以fil l在細節上。你可以把它看作構造函數的C版本。最初pthread_t對象是未初始化的,因此初始化它。

此外,您的代碼仍然可能不會始終工作,因爲您不等待線程完成。確保你的主線程不會所有的孩子之前完成:

int main() 
{ 
    initdevice(); 
    pthread_join(daemon, NULL); // wait for the thread to exit first. 
    return 0; 
} 
+0

非常感謝!爲什麼這種差異導致如此大的混亂? – Zach 2011-04-03 17:18:29

+1

@Nissim:因爲你的方式錯了!你傳遞一個初始化的指針(所以它可以指向任何東西)到一個通過指針寫入的函數(從而寫入內存中的任何地方)。 – 2011-04-03 17:20:43

1

必須分配_daemonvariablenewmalloc功能,因爲你必須使用pointer的。像下面這樣:

pthread_t* _daemon; 
_daemon = new pthread_t;