LINUX中信号量的使用
生活随笔
收集整理的這篇文章主要介紹了
LINUX中信号量的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 概述
信號量分為有名信號量(named semaphore),無名信號量(unnamed semaphore)。
(這里說的信號量主要是指semaphore.h中的信號量)
2. 函數原型
#include <semaphore.h>// 有名信號量的操作 sem_t *sem_open(const char *, int, ...); int sem_unlink(const char *); int sem_close(sem_t *);// 無名信號量的操作 int sem_init(sem_t *, int, unsigned int); int sem_destroy(sem_t *);// 獲取信號量值 int sem_getvalue(sem_t *, int *);// 發出信號,即釋放擁有權 int sem_post(sem_t *); // 等待信號,即獲取擁有權 int sem_trywait(sem_t *); int sem_wait(sem_t *);3. 用信號量解生產者-消費者問題
#include <stdio.h> #include <semaphore.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h>#define NUMBER 50000 #define CHILD 5 #define BUFSIZE 10// critical resource int fd;// semaphore sem_t* empty; sem_t* full; sem_t* mutex;void comsumer() {int buf_out = 0;int data = 0;int cnt = 0;for (int k = 0; k < NUMBER / CHILD; k++) {sem_wait(full);sem_wait(mutex);// fetch buf_outlseek(fd, BUFSIZE * sizeof(int), SEEK_SET);read(fd, (char*)&buf_out, sizeof(int));cnt++;lseek(fd, sizeof(int) * buf_out, SEEK_SET);read(fd, (char*)&data, sizeof(int));printf("%d comsume %d %d\n", getpid(), data, cnt);fflush(stdout);// write backbuf_out = (buf_out + 1) % BUFSIZE;lseek(fd, BUFSIZE * sizeof(int), SEEK_SET);write(fd, (char *)&buf_out, sizeof(int));sem_post(mutex);sem_post(empty);}printf("%d total consume %d\n", getpid(), cnt); }void producer() {int buf_in = 0;for (int i = 0 ; i < NUMBER; i++) {sem_wait(empty);sem_wait(mutex);lseek(fd, buf_in * sizeof(int), SEEK_SET);write(fd, (char*)&i, sizeof(int));buf_in = (buf_in + 1) % BUFSIZE;printf("produce %d\n", i);fflush(stdout);sem_post(mutex);sem_post(full);} }int main() {mutex = sem_open("mutex", O_CREAT | O_EXCL, 0644, 1); full = sem_open("full", O_CREAT | O_EXCL, 0644, 0); empty = sem_open("empty", O_CREAT | O_EXCL, 0644, BUFSIZE); int out_index = 0;fd = open("buffer.dat", O_CREAT | O_RDWR | O_TRUNC, 0666);lseek(fd, BUFSIZE * sizeof(int), SEEK_SET);write(fd, (char *)&(out_index), sizeof(int));pid_t p;// create producerif ((p = fork()) == 0) {producer();return 0;} else if (p < 0){printf("Fail to fork!\n");return -1;}// create comsumerfor (int j = 0; j < CHILD ; j++){if ((p = fork()) == 0) {comsumer();return 0;} else if (p < 0) {printf("Fail to fork!\n");return -1;}}int cnt = 0;printf("wait children!\n");pid_t pid;while (pid = waitpid(-1, NULL, 0)) {if (errno == ECHILD) {break;}cnt ++;printf("pid: %d end | sum: %d\n", pid, cnt);}sem_unlink("empty");sem_unlink("full");sem_unlink("mutex");return 0; }編譯命令:
g++ pcc.c -o test -lpthread參考資料
[1] 信號量
[2] semaphore.h
總結
以上是生活随笔為你收集整理的LINUX中信号量的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 球形天空盒php,unity3d天空盒
- 下一篇: 图神经网络之Node2Vec详解