Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <pthread.h>
- #include <string.h>
- #include <time.h>
- #include<stdbool.h>
- #include <math.h>
- int genRandClass()
- {
- int num = rand() % 3 + 1;
- return num;
- }
- int genRandEngine()
- {
- int num = rand() % 2;
- if (num == 0)
- {
- return 2;
- }
- else
- {
- return 4;
- }
- }
- typedef struct starShip
- {
- double starShipClass,
- numOfEngines;
- pthread_mutex_t lock;
- }starShipInstance;
- void init(starShipInstance* starShip)
- {
- starShip->starShipClass = 0;
- starShip->numOfEngines = 0;
- pthread_mutex_init(&starShip->lock, NULL);
- }
- double globalShipCount = 0;
- double globalTimeSpent = 0;
- starShipInstance starShip;
- void spawnShip(starShipInstance* currShip)
- {
- pthread_mutex_lock(&currShip->lock);
- currShip->starShipClass = (double)genRandClass();
- currShip->numOfEngines = (double)genRandEngine();
- //printf("%f\n", currShip->starShipClass);
- //printf("%f\n", currShip->numOfEngines);
- pthread_mutex_unlock(&currShip->lock);
- }
- /*double timeRefuelling(starShipInstance* currShip)
- {
- pthread_mutex_lock(&currShip->lock);
- double timeSpent;
- timeSpent = currShip->starShipClass * currShip->numOfEngines;
- pthread_mutex_unlock(&currShip->lock);
- return timeSpent;
- }*/
- int getClass(starShipInstance* starShip)
- {
- pthread_mutex_lock(&starShip->lock);
- int shipClass = starShip->starShipClass;
- pthread_mutex_unlock(&starShip->lock);
- return shipClass;
- }
- int getEngine(starShipInstance* starShip)
- {
- pthread_mutex_lock(&starShip->lock);
- int shipEngine = starShip->numOfEngines;
- pthread_mutex_unlock(&starShip->lock);
- return shipEngine;
- }
- void* fuelShip(void* vargp)
- {
- srand(time(NULL));
- for (int i = 0; i <= 10000; i++)
- {
- spawnShip(&starShip);
- globalShipCount++;
- globalTimeSpent += (getClass(&starShip) * getEngine(&starShip));
- //globalTimeSpent += timeRefuelling(&starShip);
- }
- return NULL;
- }
- int main()
- {
- pthread_t threadId[4];
- for (int i = 0; i < 4; i++)
- pthread_create(&threadId[i], NULL, fuelShip, (void*)&threadId);
- for (int i = 0; i < 4; i++)
- pthread_join(threadId[i], NULL);
- printf("\nTotal refueling time: %f centuries", globalTimeSpent);
- printf("\nTotal starship count: %f starships", globalShipCount);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement