信号量(稍微有点线程知识)(生产者消费者)
2013-07-31 20:45
141 查看
新学的信号量,自己写的生产者消费者:
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define N 10
sem_t w;
sem_t p;
int in1 = 0;
int in2 = 0;
int in = 0;
int out = 0;
int a
= {0};
void Pro()
{
while(1)
{
sleep(1);
sem_wait(&w);
a[in] = in % N;
printf("Product :%d\n",a[in]);
in++;
sem_post(&w);
sem_post(&p);
}
}
void Cus()
{
while(1)
{
sem_wait(&p);
sem_wait(&w);
a[out] = out % N;
printf("Custer :%d\n",a[out]);
out++;
sem_post(&w);
}
}
int main()
{
pthread_t thread_id1;
pthread_t thread_id2;
in1 = sem_init(&w,0,1);
in2 = sem_init(&p,0,0);
pthread_create(&thread_id1,NULL,(void *)&Pro,NULL);
pthread_create(&thread_id2,NULL,(void *)&Cus,NULL);
pthread_join(thread_id1,NULL);
pthread_join(thread_id2,NULL);
return 0;
}
新手,大神们给些意见!
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define N 10
sem_t w;
sem_t p;
int in1 = 0;
int in2 = 0;
int in = 0;
int out = 0;
int a
= {0};
void Pro()
{
while(1)
{
sleep(1);
sem_wait(&w);
a[in] = in % N;
printf("Product :%d\n",a[in]);
in++;
sem_post(&w);
sem_post(&p);
}
}
void Cus()
{
while(1)
{
sem_wait(&p);
sem_wait(&w);
a[out] = out % N;
printf("Custer :%d\n",a[out]);
out++;
sem_post(&w);
}
}
int main()
{
pthread_t thread_id1;
pthread_t thread_id2;
in1 = sem_init(&w,0,1);
in2 = sem_init(&p,0,0);
pthread_create(&thread_id1,NULL,(void *)&Pro,NULL);
pthread_create(&thread_id2,NULL,(void *)&Cus,NULL);
pthread_join(thread_id1,NULL);
pthread_join(thread_id2,NULL);
return 0;
}
新手,大神们给些意见!
相关文章推荐
- linux网络编程之posix 线程(三):posix 匿名信号量与互斥锁 示例生产者--消费者问题
- Operating System-进程/线程内部通信-信号量、PV操作的实现和应用(解决哲学家进餐和生产者消费者问题)
- 线程的相关知识、JAVA实现死锁、生产者消费者问题
- Operating System-进程/线程内部通信-信号量、PV操作的实现和应用(解决哲学家进餐和生产者消费者问题)
- linux网络编程之posix 线程(三):posix 匿名信号量与互斥锁 示例生产者--消费者问题
- linux 线程间使用信号量实现消费者生产者
- 进程与线程IPC-信号量(实现生产者消费者&哲学家就餐)
- 【线程】多线程同步互斥-条件变量与信号量,生产者与消费者问题
- 【Linux】线程总结:线程同步 -互斥锁,条件变量,信号量实现多生产者多消费者模型
- 生产者--消费者模型(线程锁方式)
- Java基础_线程_多线程_生产者消费者问题
- 线程间通讯----生产者消费者(单线程)
- Java线程(三):线程协作-生产者/消费者问题
- Java线程(三):线程协作-生产者/消费者模式 .
- Android线程—生产者和消费者
- java基础---->线程 生产者消费者问题
- 两个线程之间的同步(生产者与消费者问题)性能优化
- 生产者-消费者模型 II(信号量 环形buffer)
- 进程同步---生产者与消费者问题以及进程同步机制--信号量及P、V操作
- 线程操作之生产者及消费者