Click here to Skip to main content
11,578,524 members (60,948 online)
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C Linux Threading
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 21-May-10 23:44pm
Edited 22-May-10 4:00am
Moak11.5K
v2

1 solution

Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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:
/* ui.h */
void* display_prompt(void *id);

/* 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;
}
/* 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;
}

Smile | :)
  Permalink  

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

  Print Answers RSS
0 Peter Leow 135
1 OriginalGriff 113
2 Richard MacCutchan 85
3 Frankie-C 75
4 Afzaal Ahmad Zeeshan 75
0 OriginalGriff 904
1 Sergey Alexandrovich Kryukov 715
2 Abhinav S 573
3 F-ES Sitecore 420
4 Suvendu Shekhar Giri 393


Advertise | Privacy | Mobile
Web03 | 2.8.150603.1 | Last Updated 25 May 2010
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100