2010-05-22 110 views
2

我用c寫了一些代碼,使用pthread(我首先在eclipse IDE中配置了鏈接器和編譯器)。遠程函數與pthread

#include <pthread.h> 
#include "starter.h" 
#include "UI.h" 

Page* MM; 
Page* Disk; 
PCB* all_pcb_array; 

void* display_prompt(void *id){ 

    printf("Hello111\n"); 

    return NULL; 
} 


int main(int argc, char** argv) { 
    printf("Hello\n"); 
    pthread_t *thread = (pthread_t*) malloc (sizeof(pthread_t)); 
    pthread_create(thread, NULL, display_prompt, NULL); 
    printf("Hello\n"); 
    return 1; 
} 

工作正常。但是,當我將display_prompt移至UI.h 時,不會輸出「Hello11​​1」輸出。

有人知道如何解決這個問題嗎? Elad

回答

2

main返回時,所有線程都會終止。如果你創建的線程在那一刻沒有打印任何東西,它永遠不會。這取決於機會,而不是達到函數實現的位置。

要有main等到線程完成,使用pthread_join

int main(int argc, char** argv) { 
    printf("Hello\n"); 
    pthread_t thread; 
    pthread_create(&thread, NULL, display_prompt, NULL); 
    printf("Hello\n"); 
    pthread_join(thread); 
    return 0; 
} 

順便說一句:

  • 沒有必要爲malloc荷蘭國際集團;您可以在堆棧上創建thread
  • 如果應用程序結束時沒有錯誤,則應該從main函數返回0
+1

我覺得沒有明確返回0,而是有EXIT_SUCCESS。 – evilpie 2010-05-22 10:07:08

+0

是的。並不是說它的價值永遠不會改變,但它更加明確。 – Thomas 2010-05-22 21:00:34

+0

謝謝。 我的問題是不同的:當所有的函數都在一個文件時,它工作正常。當將display_prompt()移動到其他文件時,它不起作用。 我添加了thread_join,但現在在同一個文件中的display_prompt()不起作用時。有沒有一種特殊的方法來在Eclipse中進行調試? – 2010-05-23 11:53:22