[问题]创建多线程后printf函数的输出问题

软件和网站开发以及相关技术探讨
回复
ayjj_8109
帖子: 9
注册时间: 2007-09-05 17:44

[问题]创建多线程后printf函数的输出问题

#1

帖子 ayjj_8109 » 2008-03-30 18:23

下面的程序创建了两个线程,每个线程又各自调用了一个函数,线程执行函数和被调用的函数各有一个输出语句。
以下是程序代码和问题描述.
1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<unistd.h>
4 #include<sys/stat.h>
5 #include<sys/types.h>
6 #include<dirent.h>
7 #include<pthread.h>
8
9 void* thread_fun1(void* arge); //创建第一个线程时执行该函数
10 void* thread_fun2(void* arge); //创建第二个线程时执行该函数
11 void thread_subfun1(void); //由thread_fun1调用
12 void thread_subfun2(void); //由thread_fun2调用
13
14 int main(int argc, char* argv[], char* env[])
15 {
16 pthread_t pthread_id1, pthread_id2;
17
18 printf("This is mian function.\n");
19 pthread_create(&pthread_id1, NULL, (void*)&thread_fun1, NULL);
20 pthread_create(&pthread_id2, NULL, (void*)&thread_fun2, NULL);
21 pthread_exit(NULL);
22 }
23
24 void* thread_fun1(void* arge)
25 {
26 printf("This is thread function1.\n"); //输出语句1
27 thread_subfun1();
28 getchar();
29 pthread_exit(NULL);
30 }
31
32 void* thread_fun2(void* arge)
33 {
34 printf("This is thread function2.\n"); //输出语句2
35 thread_subfun2();
36 pthread_exit(NULL);
37 }
38
39 void thread_subfun1(void)
40 {
41 printf("This is function called by thread_fun1.\n"); //输出语句3
42 }
43
44 void thread_subfun2(void)
45 {
46 printf("This is function called by thread_fun2.\n"); //输出语句4
47 }
48 /*
49 上面的程序能输出结果:
50 This is main function.
51 This is thread function1.
52 This is function called by thread_fun1.
53 This is thread function2.
54 This is function called by thread_fun2.
55
56 可是当我把那4个输出语句,字符串最后的'\n'去掉后就只输出下面这三句句:
57 This is main function.
58 This is thread function1.This is function called by thread_fun1.
59 然后就停住了,请问这是怎么回事?
60 */
flyinflash
帖子: 2376
注册时间: 2006-09-21 14:28

#2

帖子 flyinflash » 2008-03-31 13:37

http://www.shuge.org/share/project/gent ... 4%E7%94%A8

编译型语言 C

想入门,有三本书是必看的。
《C 程序设计语言》
《Linux 程序设计》
《Unix 环境高级编程》
回复