1. 编译命令 gcc sem.c -lpthread -o sem.out
2. 执行命令 ./sem.out
3. 代码:
/* File sem.c */
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#define MAXSTACK 100
int stack[MAXSTACK][2];
int stack2[MAXSTACK][2];
int size=0;
int size2=0;
sem_t sem;
sem_t sem2;
pthread_mutex_t mut;
pthread_mutex_t mut2;
void ReadData1(void)
{
printf("ReadData1\n");
int i=0;
for (i=0; i<10; i=i+2) {
pthread_mutex_lock(&mut);
stack[size][0]=i;
stack[size][1]=i+1;
sem_post(&sem);
++size;
pthread_mutex_unlock(&mut);
}
}
void ReadData2(void)
{
printf("ReadData2\n");
int i=0;
for (i=10; i<20; i=i+2) {
pthread_mutex_lock(&mut2);
stack2[size2][0]=i;
stack2[size2][1]=i+1;
sem_post(&sem2);
++size2;
pthread_mutex_unlock(&mut2);
}
}
void HandleData1(void)
{
while(1) {
sem_wait(&sem);
pthread_mutex_lock(&mut);
--size;
printf("Plus:%d+%d=%d\n",stack[size][0],stack[size][1], stack[size][0]+stack[size][1]);
pthread_mutex_unlock(&mut);
}
}
void HandleData2(void)
{
while(1) {
sem_wait(&sem2);
pthread_mutex_lock(&mut2);
--size2;
printf("Multiply:%d*%d=%d\n",stack2[size2][0],stack2[size2][1], stack2[size2][0]*stack2[size2][1]);
pthread_mutex_unlock(&mut2);
}
}
int main(void)
{
pthread_t t1,t2,t3,t4;
sem_init(&sem,0,0);
sem_init(&sem2,0,0);
pthread_mutex_init(&mut,NULL);
pthread_mutex_init(&mut2,NULL);
pthread_create(&t4,NULL,(void *)ReadData2,NULL);
pthread_create(&t3,NULL,(void *)ReadData1,NULL);
pthread_create(&t1,NULL,(void *)HandleData1,NULL);
pthread_create(&t2,NULL,(void *)HandleData2,NULL);
//pthread_join(t1,NULL);
pthread_exit(NULL);
}