头文件:
#include <pthread.h>
创建新线程函数:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,void *(*start_routine) (void *), void *arg);
结束线程函数:
void pthread_exit(void *retval);
等待线程结束:
int pthread_join(pthread_t thread, void **retval);
创建互斥锁
pthread_mutex_t *mutex
pthread_mutex_init(互斥锁指针,NULL)
//线程互斥锁加锁
int pthread_mutex_lock(pthread_mutex_t *mutex)
//线程互斥锁解锁
int pthread_mutex_unlock(pthread_mutex_t *mutex)
//线程互斥锁销毁
int pthread_mutex_distory(pthread_mutex_t *mutex)
案例:分别用三个线程打出1-30报数
1 #include <pthread.h>
2 #include <stdio.h>
3 #include <unistd.h>
4 #include <stdlib.h>
5 //声明三个新进程
6 void* task1(void *arg);
7 void* task2(void *arg);
8 void* task3(void *arg);
9 pthread_mutex_t lock; //互斥锁指针
10 static int buf[30]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30};
11
12
13
14 int main(void)
15 {
16 int ret;
17
18 //创建初始化互斥锁
19 pthread_mutex_init(&lock,NULL);
20
21 //声明三个指针,指向线程的id
22 pthread_t tid1,tid2,tid3;
23 //创建三个新线程,用刚才的指针,
24 pthread_create(&tid1,NULL,task1,(void*)5);
25 pthread_create(&tid2,NULL,task2,(void*)6);
26 pthread_create(&tid3,NULL,task3,(void*)7);
27
28 printf("Main thread\r\n");
29 //等待线程结束运行
30 pthread_join(tid1,(void **)&ret);
31 pthread_join(tid2,(void **)&ret);
32 pthread_join(tid3,(void **)&ret);
33
34 sleep(1);
35 printf("New thread1 id:%ld\r\n",tid1);
36 printf("New thread2 id:%ld\r\n",tid2);
37 printf("New thread3 id:%ld\r\n",tid3);
38
39 //销毁互斥锁
40 pthread_mutex_destroy(&lock);
41
42 }
43
44 int i = 0;
45
46 void* task1(void *arg)
47 {
48 while(i<30){
49
50 //上锁
51 pthread_mutex_lock(&lock);
52 printf("task1:%d\r\n",buf[i]);
53 i += 1;
54 //解锁
55 pthread_mutex_unlock(&lock);
56 usleep(1);
57 }
58 pthread_exit(NULL);
59 }
60
61
62 void* task2(void *arg)
63 {
64
65 while(i<30)
66 {
67
68 //上锁
69 pthread_mutex_lock(&lock);
70 printf("task2:%d\r\n",buf[i]);
71 i += 1;
72 //解锁
73 pthread_mutex_unlock(&lock);
74 usleep(1);
75 }
76 pthread_exit(NULL);
77 }
78
79 void* task3(void *arg)
80 {
81
82 while(i<30)
83 {
84
85 //上锁
86 pthread_mutex_lock(&lock);
87 printf("task3:%d\r\n",buf[i]);
88 i += 1;
89 //解锁
90 pthread_mutex_unlock(&lock);
91 usleep(1);
92 }
93 pthread_exit(NULL);
94 }
知识兔上锁和解锁,要放在使用公共资源的前后,比如例中的 i 前后。