2010-05-22 116 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