您的位置:首页 > 其它

进程间通信机制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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  IPC 信号量
相关文章推荐