您的位置:首页 > 运维架构 > Linux

读书笔记之linux/unix系统编程手册(53)

2015-08-27 10:08 561 查看
POSIX 信号量

1.命名信号量:这种信号量拥有一个名字。通过使用相同的名字调用sem_open(),不相关的进程能够访问同一个信号量
2.未命名信号量:这种信号量没有名字,相反,它位于内存中一个预先商定的位置处。当进程之间共享时,信号量必须位于一个共享内存区域中。

3.不管是创建一个新信号量还是打开一个既有信号量,sem_open()都会返回一个指向一个sem_t值的指针,而在后续的调用中则可以通过这个指针来操作这个信号量,而在后续的调用中则可以通过这个指针来操作这个信号量

4.给新信号量创建和初始化操作是原子的

5.sem_close会终止进程与信号量之间的关系,释放系统为该进程关联到信号量上的所有资源,并递减引用该信号量的进程数

#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/sem.h>
#include <fcntl.h>
#include <semaphore.h>
#include <pthread.h>

static int n;
static sem_t *sem;

void* proFunc(void* arg)
{
while(1)
{
while(n <= 2)
{
sem_wait(sem);
++ n;
printf("%d\n", n);
sem_post(sem);
sleep(1);
}
}
return NULL;
}

void* conFunc(void* arg)
{
while(1)
{
while(n > 0)
{
sem_wait(sem);
-- n;
printf("%d\n", n);
sem_post(sem);
sleep(1);
}
}
return NULL;

}

int main(int argc, char* argv[])
{

int value;
pthread_t t[4];
n = 0;
sem = sem_open("yk", O_CREAT, 0777, 1);//name is "yk"
if(sem == SEM_FAILED)
{
perror("sem");
exit(0);
}

for(int i = 0; i < 3; ++ i)
{
if(pthread_create(t + i, NULL, proFunc, NULL) == -1)
{
perror("pthread_create");
exit(1);
}
}
for(int i = 3; i < 4; ++ i)
{
if(pthread_create(t + i, NULL, conFunc, NULL) == -1)
{
perror("pthread_create");
exit(1);
}
}

for(int i = 0; i < 4; ++ i)
{
pthread_join(t[i], NULL);
}
// if(sem_getvalue(sem, &value) == -1)
// {
// 	perror("val");
// 	exit(0);
// }
// printf("%d\n", value);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: