代码如下:

 1 #include <unistd.h>                                                                                                                                                                         
 2 #include <stdlib.h>
 3 #include <string.h>
 4 #include <pthread.h>
 5 #include <stdio.h>
 6 char message[] = "Hello world!";
 7 int runNow = 1;
 8 static int printCount = 0;
 9 
10 void *threadFunction(void *arg){
11     //int printCount = 0;
12 
13     while(printCount-- > 0){
14         if(runNow == 2){
15             printf("2");
16             runNow = 1;
17         }else{
18             sleep(1);
19         }
20     }
21     sleep(3);
22 }
23 
24 int main(int argc, char **argv)
25 {
26     pthread_t threadA;
27     int printCount1 = 0;
28     void *threadResult;
29     int res = pthread_create(&threadA, NULL, threadFunction, (void *)message);
30 
31     if(res != 0){
32         perror("Thread creation failed!");
33         exit(EXIT_FAILURE);
34     }
35 
36     while(printCount++ < 20){
37         if(runNow == 1){
38             printf("1");
39             runNow = 2;
40         }else{
41             sleep(1);
42         }
43     }
44 
45     printf("Waiting for thread to finish...\n");
46     res = pthread_join(threadA, &threadResult);
47     if(res != 0){
48         perror("Thread join failed");
49         exit(EXIT_FAILURE);
50     }
51     printf("Thread joined\n");
52 
53     exit(EXIT_SUCCESS);
54 }

编译:gcc -g thread2.c -o thread2 -lpthread

运行结果可以是以下几种:

1  thread2
12121212121212121212121Waiting for thread to finish...
Thread joined

 2 thread2
121Waiting for thread to finish...
Thread joined

 3 thread2
121Waiting for thread to finish...
Thread joined

 4 thread2
12121Waiting for thread to finish...
Thread joined

 5 thread2
121212121Waiting for thread to finish...
Thread joined

还在思索中

#include <pthread.h>
人就像是被蒙着眼推磨的驴子,生活就像一条鞭子;当鞭子抽到你背上时,你就只能一直往前走,虽然连你也不知道要走到什么时候为止,便一直这么坚持着。