1: thread_example.c
2: 01
/**
3: 02 *thread_example.c : c multiple thread programming in linux
4: 03 *author : falcon
5: 04 *E-mail : tunzhj03@st.lzu.edu.cn
6: 05 */
7: 06 #include
8: 07 #include
9: 08 #include
10: 09 #include <string.h>
11: 10 #define MAX 10
12: 11
13: 12 pthread_t thread[2];
14: 13 pthread_mutex_t mut;
15: 14 int number=0, i;
16: 15
17: 16 void *thread1()
18: 17 {
19: 18 printf ("thread1 : I'm thread 1\n");
20: 19
21: 20 for (i = 0; i < MAX; i++)
22: 21 {
23: 22 printf("thread1 : number = %d\n",number);
24: 23 pthread_mutex_lock(&mut);
25: 24 number++;
26: 25 pthread_mutex_unlock(&mut);
27: 26 sleep(2);
28: 27 }
29: 28
30: 29
31: 30 printf("thread1 :主函数在等我完成任务吗?\n");
32: 31 pthread_exit(NULL);
33: 32 }
34: 33
35: 34 void *thread2()
36: 35 {
37: 36 printf("thread2 : I'm thread 2\n");
38: 37
39: 38 for (i = 0; i < MAX; i++)
40: 39 {
41: 40 printf("thread2 : number = %d\n",number);
42: 41 pthread_mutex_lock(&mut);
43: 42 number++;
44: 43 pthread_mutex_unlock(&mut);
45: 44 sleep(3);
46: 45 }
47: 46
48: 47
49: 48 printf("thread2 :主函数在等我完成任务吗?\n");
50: 49 pthread_exit(NULL);
51: 50 }
52: 51
53: 52 void thread_create(void)
54: 53 {
55: 54 int temp;
56: 55 memset(&thread, 0, sizeof(thread)); //comment1
57: 56 //创建线程
58: 57 if((temp = pthread_create(&thread[0], NULL, thread1, NULL)) != 0) //comment2
59: 58 printf("线程1创建失败!\n");
60: 59 else
61: 60 printf("线程1被创建\n");
62: 61
63: 62 if((temp = pthread_create(&thread[1], NULL, thread2, NULL)) != 0) //comment3
64: 63 printf("线程2创建失败");
65: 64 else
66: 65 printf("线程2被创建\n");
67: 66 }
68: 67
69: 68 void thread_wait(void)
70: 69 {
71: 70 //等待线程结束
72: 71 if(thread[0] !=0) { //comment4
73: 72 pthread_join(thread[0],NULL);
74: 73 printf("线程1已经结束\n");
75: 74 }
76: 75 if(thread[1] !=0) { //comment5
77: 76 pthread_join(thread[1],NULL);
78: 77 printf("线程2已经结束\n");
79: 78 }
80: 79 }
81: 80
82: 81 int main()
83: 82 {
84: 83 //用默认属性初始化互斥锁
85: 84 pthread_mutex_init(&mut,NULL);
86: 85
87: 86 printf("我是主函数哦,我正在创建线程,呵呵\n");
88: 87 thread_create();
89: 88 printf("我是主函数哦,我正在等待线程完成任务阿,呵呵\n");
90: 89 thread_wait();
91: 90
92: 91 return 0;
93: 92 }
94: [代码] 编译和运行
95: 1 gcc -lpthread -o thread_example thread_example.c
96: 2 ./thread_example
.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }
阅读(510) | 评论(0) | 转发(0) |