#include<pthread.h>
#include<string.h>
#include<semaphore.h>
#include<errno.h>
#include<stdio.h>
#include<stdlib.h>
#define MAXSTACK 100
int stack[MAXSTACK][2];
int size=0;
sem_t sem;
int m = 0;
int n = 0;
void readdata1(void);
void readdata2(void);
void handledata1(void);
void handledata2(void);
int main()
{
pthread_t t1, t2, t3, t4;
sem_init(&sem, 0, 0);
int i;
pthread_create(&t1, NULL, (void*)handledata1, NULL);
pthread_create(&t2, NULL, (void*)handledata2, NULL);
pthread_create(&t3, NULL, (void*)readdata1, NULL);
pthread_create(&t4, NULL, (void*)readdata2, NULL);
printf("-----------------create over-----------------\n");
pthread_join(t1, NULL);
pthread_join(t2, NULL);
pthread_join(t3, NULL);
pthread_join(t4, NULL);
printf("-----------------join over-----------------\n");
sem_destroy(&sem);
return 0;
}
void readdata1(void)
{
FILE* fp;
if((fp = fopen("1.data", "r")) < 0){
printf("%s fopen failed: %s\n", __FUNCTION__, strerror(errno));
}
while(!feof(fp)){
fscanf(fp, "%d %d", &stack[size][0], &stack[size][1]);
printf("----%s: stack[%d][0][1]: %d %d \n", __FUNCTION__, size, stack[size][0], stack[size][1]);
sem_post(&sem);
size++;
}
printf("\n");
fclose(fp);
printf("%s exit\n", __FUNCTION__);
pthread_exit(0);
}
void readdata2(void)
{
FILE* fp;
if((fp = fopen("2.data", "r")) < 0){
printf("%s fopen failed: %s", __FUNCTION__, strerror(errno));
}
while(!feof(fp)){
fscanf(fp, "%d %d", &stack[size][0], &stack[size][1]);
printf("----%s: stack[%d][0][1]: %d %d \n", __FUNCTION__, size, stack[size][0], stack[size][1]);
sem_post(&sem);
size++;
}
printf("\n");
fclose(fp);
printf("%s exit\n", __FUNCTION__);
pthread_exit(0);
}
void handledata1(void)
{
while(1){
printf("%s blocked %d\n", __FUNCTION__, m);
sem_wait(&sem);
printf("%s block released %d\n", __FUNCTION__, m++);
printf("Plus: stack[%d][0][1] %d + %d = %d\n", size, stack[size][0], stack[size][1], stack[size][0]+stack[size][1]);
--size;
}
printf("%s exit\n", __FUNCTION__);
pthread_exit(0);
}
void handledata2(void)
{
while(1){
printf("%s blocked %d\n", __FUNCTION__, n);
sem_wait(&sem);
printf("%s block released %d\n", __FUNCTION__, n++);
//printf("multiply: %d * %d = %d\n", stack[size][0], stack[size][1], stack[size][0]*stack[size][0]);
printf("Multiply: stack[%d][0][1] %d * %d = %d\n", size, stack[size][0], stack[size][1], (stack[size][0])*(stack[size][1]));
--size;
}
printf("%s exit\n", __FUNCTION__);
pthread_exit(0);
}
关于线程信号量的一段小代码
最新推荐文章于 2016-04-13 21:05:44 发布