线程3——信号量

创建信号量,并赋予初值

int sem_init(sem_t *sem, int pshared, unsigned int value);


 

销毁信号量

int sem_destroy(sem_t *sem);


 

阻塞,信号量数值-1

int sem_wait(sem_t *sem);


 

非阻塞申请
int sem_trywait(sem_t *sem);


 

计时申请一个信号量
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);


 

发送信号量,数值 +1
int sem_post(sem_t *sem);


 

获取信号量值

int sem_getvalue(sem_t *sem, int *sval);


 示例:和互斥锁案例相同

 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <stdlib.h>
 4 #include <semaphore.h>
 5 
 6 
 7 void* task1(void *arg);
 8 void* task2(void *arg);
 9 void* task3(void *arg);
10 
11 static int i = 10 ;
12 static sem_t sem;            //信号量指针
13 
14 
15 int main(void)
16 {
17     int ret;
18     sem_init(&sem,0,1);    //初始化信号量 初值为1
19     
20     //声明三个指针,指向线程的id
21     pthread_t tid1,tid2,tid3;
22     //创建三个新线程,用刚才的指针,
23     pthread_create(&tid1,NULL,task1,(void*)5);
24     pthread_create(&tid2,NULL,task2,(void*)6);
25     pthread_create(&tid3,NULL,task3,(void*)7);
26     
27     printf("Main thread\r\n");
28     //等待线程结束运行
29     pthread_join(tid1,(void **)&ret);
30     pthread_join(tid2,(void **)&ret);
31     pthread_join(tid3,(void **)&ret);
32     
33     sleep(1);
34     printf("New thread1 id:%ld\r\n",tid1);
35     printf("New thread2 id:%ld\r\n",tid2);
36     printf("New thread3 id:%ld\r\n",tid3);
37     //销毁信号量
38     sem_destroy(&sem);
39     
40 
41 }
42 
43 void* task1(void *arg)
44 {
45     while(i<30){
46     //信号量-1
47     sem_wait(&sem);    
48     i++;
49     printf("%d\r\n",i);
50     //信号量+1
51     sem_post(&sem);
52     usleep(1);
53     }
54     pthread_exit(NULL);
55     
56 }
57 
58 void* task2(void *arg)
59 {
60     while(i<30){
61     //信号量-1
62     sem_wait(&sem);    
63     i++;
64     printf("%d\r\n",i);
65     //信号量+1
66     sem_post(&sem);
67     usleep(1);
68     }
69     pthread_exit(NULL);
70     
71 }
72 
73 void* task3(void *arg)
74 {
75     while(i<30){
76     //信号量-1
77     sem_wait(&sem);    
78     i++;
79     printf("%d\r\n",i);
80     //信号量+1
81     sem_post(&sem);
82     usleep(1);
83     }
84     pthread_exit(NULL);
85     
86 }

计时申请信号量:(结构体见上一篇条件变量)

1 struct timeval now;
2 struct timespec outtime;
3 gettimeofday(&now, NULL);//获取当前时间
4 outtime.tv_sec = now.tv_sec + 5; //设定唤醒的绝对时间是当前时间+5s
5 outtime.tv_nsec = now.tv_usec * 1000;
6 sem_timedwait(&sem, &outtime);

 

posted @ 2019-10-14 21:18  祁峰_1024  阅读(154)  评论(0编辑  收藏  举报