Click here to Skip to main content
15,889,356 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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 function display_prompt() to UI.h no "Hello111 " output is printed.

Anyone knows how to solve that?
Elad
Posted
Updated 22-May-10 4:00am
v2

1 solution

elad2109 wrote:
However, when I move function display_prompt() to UI.h


You move...What?
You should move just the function prototype to the header file.


However, with the main you provided, the output is (almost) unpredictable, since the main function may exit well before the thread has a chance to produce its output.
Try this code:
C
/* ui.h */
void* display_prompt(void *id);


C
/* ui.c */
#include <stdio.h>
#include "ui.h"
void* display_prompt(void *id){
    int i;
    for (i=0;i<10; i++)
    {
      printf("Secondary thread %d\n", i);
      sleep(2);
    }
    return NULL;
}

C
/* main source file */
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include "ui.h"


int main(int argc, char** argv) {
    int i;
    printf("Hello\n");
    pthread_t *thread = (pthread_t*) malloc (sizeof(pthread_t));
    if (!thread ) return -1;
    pthread_create(thread, NULL, display_prompt, NULL);
    for (i=0; i<10; i++)
    {
      printf("Main Thread %d\n", i);
      sleep(1);
    }
    free(thread);
    return 1;
}


:)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900