#include<stdlib.h>
#include<stdio.h>
#include<semaphore.h>
#include<error.h>
#define MAXSIZE 100
int Stack[MAXSIZE][2];
int size=0;
sem_t sem;
void *read_data1(void *arg)
{
FILE *fp;
fp=fopen("1.dat","r");
if(fp==NULL)
{
printf("Can not open file \n");
}
while(!feof(fp))
{
fscanf(fp,"%d %d",&Stack[size][0],&Stack[size][1]);
printf("In function read_data:Stack[%d]=%d,Stack[%d]=%d\n",size,Stack[size][0],size,Stack[size][1]);
sem_post(&sem);
size++;
}
fclose(fp);
}
void *read_data2(void *arg)
{
FILE *fp;
fp=fopen("2.dat","r");
if(fp==NULL)
{
printf("Can not open file \n");
}
while(!feof(fp))
{
fscanf(fp,"%d %d",&Stack[size][0],&Stack[size][1]);
printf("In function read_data:Stack[%d]=%d,Stack[%d]=%d\n",size,Stack[size][0],size,Stack[size][1]);
sem_post(&sem);
size++;
}
fclose(fp);
}
void *add_thread(void *arg)
{
while(1)
{
sem_wait(&sem);
printf("Stack[%d](%d)+Stack[%d](%d) = %d\n",size,Stack[size][0],size,Stack[size][1],Stack[size][0]+Stack[size][1]);
size--;
}
}
void *multi_thread(void *arg)
{
while(1)
{ printf("multipler!\n");
sem_wait(&sem);
printf("Stack[%d](%d)*Stack[%d](%d) = %d\n",size,Stack[size][0],size,Stack[size][1],Stack[size][0]*Stack[size][1]);
size--;
}
}
int main()
{
pthread_t t1,t2,t3,t4;
sem_init(&sem,0,0);
pthread_create(&t1,NULL,read_data1,NULL);
pthread_create(&t2,NULL,read_data2,NULL);
//pthread_create(&t3,NULL,add_thread,NULL);
pthread_create(&t4,NULL,multi_thread,NULL);
pthread_join(t1,NULL);
pthread_join(t2,NULL);
pthread_join(t3,NULL);
pthread_join(t4,NULL);
return 0;
}
|