Fork me on GitHub

多线程

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <pthread.h>
 4 #include <errno.h>
 5 #include <string.h>
 6 #include <unistd.h>
 7 
 8 //void test()
 9 //{
10 //    pthread_exit(NULL);      //终止线程的用法
11 //}
12 
13 //void* func1(void* arg)
14 //{
15 //    printf("pthread1 start\n");
16 //    test();
17 //    sleep(1);
18 //    printf("pthread1 end\n");
19 //    return NULL;
20 //}
21 
22 void* func2(void* arg)
23 {
24     int* p = (int* )arg;
25     int i = *p;
26     free(p);
27 
28     printf("pthread%d start\n",i);
29     while(1)
30     {
31         printf("pthread%d @@@@@@@@@\n",i);
32         sleep(1);
33     }
34 
35     printf("pthread2 end%d \n",i);
36 }
37 
38 void createthr()
39 {
40     pthread_t thrd1,thrd2;
41 
42 //    static int i1 = 1;
43 //    static int i2 = 2;
44 
45     int *i1 = malloc(sizeof(int));
46     int *i2 = malloc(sizeof(int));
47     *i1 =1;
48     *i2 =2;
49 
50     if (pthread_create(&thrd1,NULL,func2,i1)!=0)
51     {
52         printf("error is %s\n",strerror(errno));
53     }
54     if (pthread_create(&thrd2,NULL,func2,i2)!=0)
55     {
56         printf("error is %s\n",strerror(errno));
57     }
58 
59 
60     return;
61 }
62 
63 
64 int main(void)
65 {
66     createthr();
67 
68     while(1)
69     {
70         sleep(1);
71     }
72 
73     return EXIT_SUCCESS;
74 }

 ps:

pthread_join(thrd1,NULL); //主线程挂起,等待thrd1退出
pthread_join(thrd2,NULL);
printf("main end\n");

 

posted @ 2016-08-01 17:13  千秋此意  阅读(160)  评论(0编辑  收藏  举报