#include <stdio.h>
#include "mythreads.h"
#include <stdlib.h>
#include <pthread.h>
void *
mythread(void *arg) {
printf("%s\n", (char *) arg);
return NULL;
}
int
main(int argc, char *argv[])
{
if (argc != 1) {
fprintf(stderr, "usage: main\n");
exit(1);
}
pthread_t p1, p2;
printf("main: begin\n");
Pthread_create(&p1, NULL, mythread, "A");
Pthread_create(&p2, NULL, mythread, "B");
// join waits for the threads to finish
//Pthread_join(p1, NULL);
//Pthread_join(p2, NULL);
printf("main: end\n");
return 0;
}
This is a code from Remzi Chapter 27. Playing around, I'm curious to know why sometimes on run, I get A printed twice. I know why this is happening, because I haven't included the join statement. Why should skipping join cause this?
My output:
shubham@HP:~/OS/Code-Threads-Intro$ ./a.out
main: begin
A
main: end
B
shubham@HP:~/OS/Code-Threads-Intro$ ./a.out
main: begin
A
main: end
B
shubham@HP:~/OS/Code-Threads-Intro$ ./a.out
main: begin
main: end
A
shubham@HP:~/OS/Code-Threads-Intro$ ./a.out
main: begin
main: end
B
A
A
Removing the call the pthread_join()
should not cause "A" to be printed twice. (Barring a bug in the implementation.)
But since your fprintf()
calls share the same FILE *
structure, they may not be not multithread-safe. How and why they could print "A" twice is dependent upon the implementation details of your system's fprintf()
function.