rendered paste body#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#define DEBUG 1
#define MAX_DATA 12
typedef struct subway{
double nStartDistance[4];
double nNowDistance[4];
double nSpeed[4];
}subway_t;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
void Usage();
void PrintList(int CurrentSubway);
subway_t value;
char *pProgname;
char *pFilename;
void *GoSubwayGo(void *index)
{
clock_t start, stop;
double diff;
int Subway;
int Status;
int GotThere = 1;
Status = pthread_mutex_lock(&mutex);
Subway = atoi((char*) index);
printf("Subway %d started\n", Subway+1);
while (GotThere != 0)
{
printf("Subway: %d\n", Subway+1);
start = clock();
diff = difftime(stop = clock(), start);
if(value.nNowDistance[Subway] >= value.nSpeed[Subway])
{
value.nNowDistance[Subway] = value.nNowDistance[Subway] - value.nSpeed[Subway];
}
else value.nNowDistance[Subway] = 0;
GotThere = value.nNowDistance[Subway];
}
Status = pthread_mutex_unlock(&mutex);
pthread_exit((void *) 0);
}
int main(int argc, char *argv[])
{
FILE *file;
char cBuffer[MAX_DATA];
int nCount;
pthread_t th[20];
pProgname = argv[0];
if(argc != 2)
{
Usage();
return EXIT_FAILURE;
}
pFilename = argv[1];
if((file = fopen(pFilename, "r")) == NULL)
{
fprintf(stderr, "%s: Can't open file %s\n", pProgname, pFilename);
return EXIT_FAILURE;
}
for(nCount = 0; nCount < 4; nCount++)
{
if(fgets(cBuffer, MAX_DATA -1, file) == NULL)
{
fprintf(stderr, "%s: invalid file layout %s\n", pProgname, pFilename);
return EXIT_FAILURE;
}
sscanf(cBuffer,"%lf %lf", &value.nStartDistance[nCount], &value.nSpeed[nCount]);
value.nNowDistance[nCount] = value.nStartDistance[nCount] * 1000;
value.nSpeed[nCount] = value.nSpeed[nCount] / 3.6;
}
#if DEBUG
for(nCount = 0; nCount < 4; nCount++) PrintList(nCount);
#endif
while((cBuffer[0] = getchar()) != 'S')
{
continue;
}
for(nCount = 0; nCount < 4; nCount++)
{
sprintf(cBuffer,"%d",nCount);
if(pthread_create(&th[nCount], NULL, &GoSubwayGo, cBuffer) != 0)
{
fprintf(stderr, "%s: Error creating Thread\n", pProgname);
return EXIT_FAILURE;
}
}
for(nCount = 0; nCount < 4; nCount++)
{
pthread_join(th[nCount], NULL);
}
#if DEBUG
for(nCount = 0; nCount < 4; nCount++) PrintList(nCount);
#endif
return EXIT_SUCCESS;
}
void PrintList(int CurrentSubway)
{
printf("%d: StartDistance: %.2lf km, NowDistance: %.2lf m, Speed: %.2lf m/s\n",
CurrentSubway, value.nStartDistance[CurrentSubway], value.nNowDistance[CurrentSubway], value.nSpeed[CurrentSubway]);
}
void Usage()
{
printf("Usage %s:\n", pProgname);
printf("%s filename\n", pProgname);
}