进程间通信机制01_信号量
2018-01-26 19:32
344 查看
一.信号量的定义:
它是一个特殊变量,只允许对它进行等待(wait)和发送信号(signal)这两种操作。最简单的信号量是只能取值0和1的变量,即二进制信号量。可以取多个正整数值的信号量被称为通用信号量。二.linux信号量机制:
1.semget函数:
(1)原型:int semget(key_t key, int num_sems, int sem_flags);
(2)作用:创建一个新信号量或取得一个已有信号量的键。
2.semop函数:
(1)原型:int semget(int sem_id, struct sembuf *sem_ops, size_t num_sem_ops);
(2)作用:用于改变信号量的值。
3.semctl函数:
(1)原型:int semctl(int sem_id, int sem_num, int command...);
(2)作用:用来直接控制信号量信息。
三.例子:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <pthread.h> #include <semaphore.h> void *thread_function(void *arg); sem_t bin_sem; #define WORK_SIZE 1024 char work_area[WORK_SIZE]; int main() { int res; pthread_t a_thread; void *thread_result; res = sem_init(&bin_sem, 0, 0); if (res != 0) { perror("Semophore initialization failed."); exit(EXIT_FAILURE); } res = pthread_create(&a_thread, NULL, thread_function, NULL); if (res != 0) { perror("Thread create failed."); exit(EXIT_FAILURE); } printf("Input some text. Enter 'end' to finish.\n"); while (strncmp("end", work_area, 3) != 0) { fgets(work_area, WORK_SIZE, stdin); sem_post(&bin_sem); } printf("\nWaiting for thread to finish...\n"); res = pthread_join(a_thread, &thread_result); if (res != 0) { perror("Thread join failed.\n"); exit(EXIT_FAILURE); } printf("Thread joind\n"); sem_destroy(&bin_sem); exit(EXIT_SUCCESS); return 0; } void *thread_function(void *arg) { sem_wait(&bin_sem); while (strncmp("end", work_area, 3) != 0) { printf("You input %d characters\n", (int)strlen(work_area) - 1); sem_wait(&bin_sem); } pthread_exit(NULL); }
相关文章推荐
- 进程间通信机制(管道、信号、共享内存/信号量/消息队列)、线程间通信机制(互斥锁、条件变量、posix匿名信号量)
- 进程间通信机制(管道、信号、共享内存/信号量/消息队列)、线程间通信机制(互斥锁、条件变量、posix匿名信号量)
- linux进程间通信机制(消息队列,信号量,共享内存)
- 进程间通信机制(管道、信号、共享内存/信号量/消息队列)、线程间通信机制(互斥锁、条件变量、posix匿名信号量)
- Linux C编程--进程间通信(IPC)5--System V IPC 机制2--信号量
- Linux C编程--进程间通信(IPC)5--System V IPC 机制2--信号量
- linux 信号量 机制 详解之一 进程间通信semget semop semctl
- 进程间通信机制(管道、信号、共享内存/信号量/消息队列)、线程间通信机制(互斥锁、条件变量、posix匿名信号量)
- 线程间同步机制01_信号量
- 进程间通信机制之二:信号量
- Linux C编程--进程间通信(IPC)5--System V IPC 机制2--信号量
- 进程间通信--IPC信号量
- 下面哪些机制可以用于进程间通信
- Android进程间通信(IPC)机制Binder简要介绍和学习计划
- Android进程间通信(IPC)机制Binder简要介绍和学习计划【转】
- 进程间通信:用信号量实现对共享内存读写顺序的控制
- Android系统进程间通信(IPC)机制Binder中的Client获得Server远程接口过程源代码分析
- 浅谈Android系统进程间通信(IPC)机制Binder中的Server和Client获得Service Manager接口之路
- iOS-浅谈runtime运行时机制01-类与对象的内部结构
- 进程间通信----信号量