Click here to Skip to main content
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 22-May-10 0:44am
Edited 22-May-10 5:00am
Moak11.4K
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 Zoltán Zörgő 300
1 /\jmot 205
2 Peter Leow 165
3 CHill60 145
4 CPallini 135
0 Sergey Alexandrovich Kryukov 9,383
1 OriginalGriff 6,881
2 Peter Leow 4,607
3 Zoltán Zörgő 4,284
4 CHill60 2,892


Advertise | Privacy | Mobile
Web03 | 2.8.150129.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