信号量
信号量(信号灯)
mutex初始化为1
lock之后为0
unlock之后为1
mutex实现的同步都是串行的
sem相当于有多个mutex, 并行
(1) 头文件: semaphore.h
(2) 信号量类型: sem_t; 加强版互斥锁
(3) 主要函数
初始化信号量:int sem_init(sem_t *sem, int pshared, unsigned int value);
0 线程同步
1 进程同步
value: 最多有几个线程操作共享数据
销毁信号int sem_destroy(sem_t *sem);
加锁
int sem_wait(sem_t *sem);
调用一次相当于对sem做了-1操作
如果sem值为0, 线程会阻塞
int sem_trywait(sem_t *sem);
尝试加锁, 不阻塞, 直接返回
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
限时加锁
解锁int sem_post(sem_t *sem);
(4) 使用信号量实现生产者, 消费者模型
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
sem_t produce_sem;
sem_t custom_sem;
typedef struct node {
int data;
struct node *next;
}Node;
Node *head = NULL;
void* producer(void *arg) {
while (1) {
sem_wait(&produce_sem);
Node *node = (Node *)malloc(sizeof(Node));
node->data = rand() % 1000;
node->next = head;
head = node;
printf("++++生产者: %lu, %d\n", pthread_self(), node->data);
sem_post(&custom_sem);
sleep(rand()%5);
}
return NULL;
}
void* customer(void *arg) {
while (1) {
sem_wait(&custom_sem);
Node *del = head;
head = head->next;
printf("----消费者: %lu, %d\n", pthread_self(), del->data);
free(del);
sem_post(&produce_sem);
sleep(rand()%5);
}
return NULL;
}
int main(int argc, const char *argv[]) {
pthread_t thid[2];
// 初始化信号量
sem_init(&produce_sem, 0, 4);
sem_init(&custom_sem, 0, 0);
pthread_create(&thid[0], NULL, producer, NULL);
pthread_create(&thid[1], NULL, customer, NULL);
for (int i = 0; i < 2; i++) {
pthread_join(thid[i], NULL);
}
sem_destroy(&produce_sem);
sem_destroy(&custom_sem);
return 0;
}