1
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>
#include <time.h>
struct msg
{
char buf[20];
sem_t full;
sem_t empty;
}data;
//生产者
void *produce(void *v)
{
char *buf[]={"苹果","香蕉","芒果","荔枝","猕猴桃","西瓜","桃子","葡萄"};
int len = sizeof(buf)/sizeof(buf[0]);
while(1)
{
sem_wait(&data.empty); // p
usleep(10000*(rand()%10+1));
strcpy(data.buf,buf[rand()%len]);
sem_post(&data.full); // v
}
}
//消费者
void *consume(void* v)
{
long num = (long)v;
while(1)
{
sem_wait(&data.full); // p
usleep(10000*(rand()%10+1));
printf("%ld消费者吃了一个%s\n",num,data.buf);
data.buf[0] = '\0';
sem_post(&data.empty); // v
}
}
int main(int argc,char **argv)
{
srand((unsigned int)time(NULL));
long i;
pthread_t thread;
for(i = 0;i < 4;i++)
{
pthread_create(&thread, NULL, consume, (void*)(i+1));
pthread_detach(thread);
}
pthread_create(&thread, NULL, produce, NULL);
pthread_detach(thread);
sem_init(&data.full,0,0);
sem_init(&data.empty,0,1);
pthread_exit(NULL);
}
2
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>
#include <time.h>
struct msg
{
char *buf[10];
sem_t full;
sem_t empty;
int count;
}data;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;//互斥锁
//生产者
void *produce(void *v)
{
char *buf[]={"苹果","香蕉","芒果","荔枝","猕猴桃","西瓜","桃子","葡萄","甘蔗","石榴"};
int len = sizeof(buf)/sizeof(buf[0]);
while(1)
{
usleep(100000*(rand()%10+1));
sem_wait(&data.empty); // p
pthread_mutex_lock(&mutex);
data.buf[data.count]=buf[rand()%len];
data.count++;
pthread_mutex_unlock(&mutex);
sem_post(&data.full); // v
}
}
//消费者
void *consume(void* v)
{
long num = (long)v;
while(1)
{
usleep(100000*(rand()%10+1));
sem_wait(&data.full); // p
pthread_mutex_lock(&mutex);
int index = rand()%data.count;
printf("%ld消费者吃了一个%s 剩余个数:%d\n",num,data.buf[index],data.count-1);
data.count--;
char *tmp = data.buf[index];
data.buf[index] = data.buf[data.count];
data.buf[data.count] = tmp;
pthread_mutex_unlock(&mutex);
sem_post(&data.empty); // v
}
}
int main(int argc,char **argv)
{
srand((unsigned int)time(NULL));
long i;
pthread_t thread;
for(i = 0;i < 4;i++)
{
pthread_create(&thread, NULL, consume, (void*)(i+1));
pthread_detach(thread);
}
for(i = 0;i < 4;i++)
{
pthread_create(&thread, NULL, produce, NULL);
pthread_detach(thread);
}
sem_init(&data.full,0,0);
sem_init(&data.empty,0,10);
pthread_exit(NULL);