fopen problem in multi-thread (detach)
Hi,
I write a simple multi-thread programming. In such thread, I only open file to write a text, then end thread. When I run program, the thread is dead immediately after fopen. Sometimes, it works, sometimes, it deads. Any idea to share?
int main(int argc, char *argv[]) {
pthread_t thread1;
int *iptr1;
printf("Program Starts.\n");
iptr1 = malloc(sizeof(int));
pthread_create(&thread1, NULL, (void *) process_fopen, (void *) iptr1);
printf("main end\n");
return 0;
}
void process_fopen(void * tmp) {
int i;
FILE *fpTest2 = NULL;
char x[10]="Thread_XXX";
i = *((int *) tmp);
free(tmp);
pthread_detach(pthread_self());
printf("I'm in thread\n");
fpTest2 = fopen("./kkk.txt", "wt");
printf("After fopen\n");
if (fpTest2 == NULL) {
printf("ERROR\n");
} else {
printf("2 Confirm Open Success\n");
fwrite(x, sizeof(x[0]), sizeof(x)/sizeof(x[0]), fpTest2);
}//end else
fclose(fpTest2);
printf("thread end\n");
}
the output, it shows
Program Starts.
I'm in thread
that's all, no other printf message. NO such kkk.txt file. I'm quite in doubt. This is a simple program. Do I make any mistake?
When I run this program several times, sometimes it works too. It creates kkk.txt and show those correct printf messages.
Program Starts.
I'm in thread
After fopen
2 Confirm Open Success
thread end
I'm really need some help to get me out of this.
Thanks in advance.
EDIT:
I've tried by removing
pthread_detach(pthread_self());
and put this statement in main
pthread_join(thread1, NULL);
The program works successfully. Everytime, fopen has no problem.
I guess that I'm not clear with pthread_detach(pthread_self()); concept. Any suggestion?
Last edited by joey123; 09-28-2009 at 09:05 PM.
Reason: Add more information
|