#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;
}
这是来自Remzi第 27 章的代码。四处玩耍,我很想知道为什么有时在运行时,我会打印两次 A。我知道为什么会这样,因为我没有包含 join 语句。为什么跳过加入会导致这种情况?
我的输出:
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