views:

25

answers:

1

Hi all,

I wrote some code in c, using pthread (I configured the linker and compiler in eclipse IDE first).

#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;
}

that works fine. However, when I move display_prompt to UI.h no "Hello111 " output is printed.

anyone know how to solve that? Elad

+2  A: 

When main returns, all threads terminate. If the thread you created hasn't printed anything at that moment, it never will. This is up to chance, not up to the location of the function's implementation.

To have main wait until the thread is done, use 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;
}

By the way:

  • There's no need for mallocing; you can just create thread on the stack.
  • You should return 0 from your main function if it ended without an error.
Thomas
I feel better without explicitly returning 0, instead there is EXIT_SUCCESS.
evilpie
True. Not that its value is ever going to change, but it's a bit more explicit.
Thomas
thanks. My problem was different: It worked fine when all the function were at one file. When moved display_prompt() to other file it didn't work.I added the thread_join, but now when display_prompt() in the same file doesn't work. Is there a special way to debug that in Eclipse?