您的位置:首页 > 其它

Usage sample of unix semaphore

2010-01-10 14:04 393 查看
There are two types of semaphore on unix system:

-- System V信号量(命名信号量)

#include <sys/sem.h>

int semctl(int sem_id, int sem_num, int command, ...);

int semget(key_t key, int num_sems, int sem_flags);

int semop(int sem_id, struct sembuf *sem_ops, size_t num_sem_ops);

-- POSIX无名信号量

int sem_init(sem_t *sem, int pshared, unsigned int value);

int sem_wait(sem_t * sem);

int sem_trywait(sem_t * sem);

int sem_post(sem_t * sem);

int sem_getvalue(sem_t * sem, int * sval);

int sem_destroy(sem_t * sem);

无名信号量不能用在进程间通信, 命名信号量可以用在进程间通信。

-- Sample program of POXIS semaphore --

#include <pthread.h>

#include <semaphore.h>

#include <stdio.h>

#include <unistd.h>

int data;

sem_t sem;

void *HandleDataWrite(void *args)

{

while(true)

{

sleep(2);

sem_post(&sem);

data=100;

}

return NULL;

}

void *HandleDataRead(void *args)

{

while(true)

{

sleep(3);

sem_wait(&sem);

printf("Data=%d/n",data);

}

return NULL;

}

int main(void){

pthread_t tread,twrite;

sem_init(&sem,true,0);

pthread_create(&tread,NULL,HandleDataRead,NULL);

pthread_create(&twrite,NULL,HandleDataWrite,NULL);

pthread_join(tread,NULL);

pthread_join(twrite,NULL);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: