linux信号量
来源:互联网 发布:转运物品 淘宝 编辑:程序博客网 时间:2024/06/06 20:36
API
int sem_init(sem_t *sem, int pshared, unsigned int value);
int sem_destroy(sem_t *sem);
int sem_wait(sem_t *sem);
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
Link with -pthread.
应用
sem_t sem_id1, sem_id2;
void* thread_one_fun(void *arg)
{
sem_wait(&sem_id1);
printf("thread_one have the semaphore\n");
number++;
printf("number = %d\n",number);
sem_post(&sem_id2);
}
void* thread_two_fun(void *arg)
{
sem_wait(&sem_id2);
printf("thread_two have the semaphore \n");
number--;
printf("number = %d\n",number);
sem_post(&sem_id1);
}
int main(int argc,char *argv[])
{
number = 1;
pthread_t id1, id2;
sem_init(&sem_id1, 0, 1); // 空闲的
sem_init(&sem_id2, 0, 0); // 忙的
pthread_create(&id1,NULL,thread_one_fun, NULL);
pthread_create(&id2,NULL,thread_two_fun, NULL);
pthread_join(id1,NULL);
pthread_join(id2,NULL);
printf("main,,,\n");
return 0;
}
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
#define BUFF_SIZE 10
char buffer[BUFF_SIZE];
char count; // 缓冲池里的信息数目
sem_t sem_mutex; // 生产者和消费者的互斥锁
sem_t p_sem_mutex; // 空的时候,对消费者不可进
sem_t c_sem_mutex; // 满的时候,对生产者不可进
void * Producer()
{
while(1)
{
sem_wait(&p_sem_mutex); //当缓冲池未满时
sem_wait(&sem_mutex); //等待缓冲池空闲
count++;
sem_post(&sem_mutex);
if(count < BUFF_SIZE)//缓冲池未满
sem_post(&p_sem_mutex);
if(count > 0) //缓冲池不为空
sem_post(&c_sem_mutex);
}
}
void * Consumer()
{
while(1)
{
sem_wait(&c_sem_mutex);//缓冲池未空时
sem_wait(&sem_mutex); //等待缓冲池空闲
count--;
sem_post(&sem_mutex);
if(count > 0)
sem_post(c_sem_nutex);
}
}
int main()
{
pthread_t ptid,ctid;
//initialize the semaphores
sem_init(&empty_sem_mutex,0,1);
sem_init(&full_sem_mutex,0,0);
//creating producer and consumer threads
if(pthread_create(&ptid, NULL,Producer, NULL))
{
printf("\n ERROR creating thread 1");
exit(1);
}
if(pthread_create(&ctid, NULL,Consumer, NULL))
{
printf("\n ERROR creating thread 2");
exit(1);
}
if(pthread_join(ptid, NULL)) /* wait for the producer to finish */
{
printf("\n ERROR joining thread");
exit(1);
}
if(pthread_join(ctid, NULL)) /* wait for consumer to finish */
{
printf("\n ERROR joining thread");
exit(1);
}
sem_destroy(&empty_sem_mutex);
sem_destroy(&full_sem_mutex);
//exit the main thread
pthread_exit(NULL);
return 1;
}
- linux信号量
- linux 信号量
- linux 信号量
- Linux信号量
- linux信号量
- linux 信号量
- Linux信号量
- Linux信号量
- linux信号量
- linux 信号量
- linux 信号量
- Linux 信号量
- linux信号量
- linux 信号量
- Linux 信号量
- Linux 信号量
- linux信号量
- linux 信号量
- TortoiseGit学习笔记(三)
- jQuery动画---显示、卷动、淡入淡出
- ARC forbids explicit message sendof'dealloc'
- var let 和const
- NGUI文字闪烁效果
- linux信号量
- 清除win+r的记录
- nginx过滤IP访问
- 日志库EasyLogging++学习系列(6)—— 日志记录器
- css3写下拉列表展开
- Android ListView与RecyclerView对比浅析--缓存机制
- 使用mysql 统计函数 结果为null时返回值改为0
- hadoop学习笔记
- springmvc 中使用fastjson 反序列化json,导致时区相差的问题