Click here to Skip to main content
15,906,766 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to implement a code which creates a thread. The thread writes into a file. If the thread has been created it returns 0 . The code here returns 0 but it does go into the fuction write() but does not writes in the file . Just to check it goes in the function i have put a printf() statement . Here is the code :-
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

void *write(void *arg)
{

  printf("HI \n");
  FILE *fp;
  fp=fopen("file.txt","a");

  if(fp==NULL)
    {
      printf("error\n");
    }
else{
  fprintf(fp,"hello world");
  
 }
main()
{
  pthread_t thread;
  int tid;
  tid=pthread_create(&thread,NULL,write,NULL);
  printf("thread1 return %d \n",tid);
  exit(0);
}
Posted

1 solution

The main need not to exit before the thread finishes so we have to add another function in main pthead_join () . Here is the edited code
C#
  main()
{
  thread_t thread;
  int tid;
  tid=pthread_create(&thread,NULL,write,NULL);
  printf("thread1 return %d \n",tid);
  pthread_join(thread, NULL);
  exit(0);
}
 
Share this answer
 
Comments
pasztorpisti 25-Aug-13 6:45am    
Every thread has an owner and every started thread must be joined by the owner at some point before the termination of the application. The termination of the application in case of native application happens either by calling an exit() like function or by returning from the main function with the main thread. In some (modern) languages the process doesn't disappear until the termination of any non-daemon threads.

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