2

I'm working on building a process scheduler that follows the FIFO algorithm. I've written all the code and it is working, except for the part of the report. Here an example of how the report is coming out:

FIFO PROCESS SCHEDULER
Simulation # Report:  
- Schedule Simulation Algorithm: FIFO  
- Number of process: 3  
- Start Time: 19/12/2012 02:54:09 ***<-HERE WORKS!!!!***  
- Duration: 40.0 seconds  
- Simulation Outflow: 0.075000 process / second  
- Total Block Time: 10 seconds  
Processes # Report:  
- Process Number: 0  
- Start Time: 15:51:44 4452907-04-04  ***<- HERE DON'T!!!!***  
- Duration: -140458013347901.0 seconds  
- End Time: 12/31/1969 21:00:03  
- Blocked Time: 10 seconds  
- Executed Time: 1 seconds  
Processes # Report:  
- Process Number: 1  
- Start Time: 14/03/1970 19:00:32  ***<- AND SO ON...***  
- Duration: 140458002575076.0 seconds  
- End Time: 21:25:08 4452907-02-11  
- Blocked Time: 0 seconds  
- Executed Time: 13 seconds  
Processes # Report:  
- Process Number: 2  
- Start Time: 14/03/1970 19:00:32  
- Duration: 140458002575076.0 seconds  
- End Time: 21:25:08 4452907-02-11  
- Blocked Time: 0 seconds  
- Executed Time: 16 seconds 

Why the times from processes have strange values and the simulator time don't?
thanks in advance.

Here the C code


#include<stdlib.h>
#include<stdio.h>
#include<pthread.h>
#include<semaphore.h>
#include<time.h>
#include<string.h>

#define PROCESS_NUM_MIN         1
#define PROCESS_NUM_MAX         3
#define PROCESS_TIME_EXEC_MIN   3
#define PROCESS_TIME_EXEC_MAX   20
#define PROCESS_BLOCK_TIME_MIN  2
#define PROCESS_BLOCK_TIME_MAX  10

typedef struct process {
    time_t  startTime;
    time_t  endTime;
    double  durationTime;
    int     totalTime;
    int     execTime;
    int     gonaBlock;
    int     blockTime;

} Process;

typedef struct simulatorTimeInfo {
    time_t  startTime;
    time_t  endTime;
    int     mediumReturnTime;
    int     mediumAnswerTime;
    int     blockTime;
    int     simulationDuration;
} SimulatorTimeInfo;

void    initProcessScheduler();
void    *schedulerExecute();
Process getBufferedProcess(int position);
int     compareBufferCount(int position);
void    processExecute(Process process);
void    showReport();
void    showSimulationReport();
void    showProcessesReport();

Process createProcess(int count);
int     determineProcessBlock(int count);
void    allocateProcess(Process process, int position);
void    *processFactoryExecute();

int     ramdomNumber(int max, int min);
int     rdtsc();

time_t  getSystemTimeNow();
void    printSystemTime(time_t t);      

sem_t   bufferMutex;
sem_t   bufferCount;

pthread_t   processFactoryThread;
pthread_t   schedulerThread;

Process             processBufferVector[PROCESS_NUM_MAX];
SimulatorTimeInfo   simulatorTimeInfo;

int     numberOfProcess;
int     numberOfProcessToBlock;

int main(int argc, char **argv) {
    //get simulation start time         
    simulatorTimeInfo.startTime = getSystemTimeNow();

    printf("FIFO PROCESS SCHEDULER - Matheus Arleson\n");

    //starting semaphores
    sem_init(&bufferMutex, 0, 1);
    sem_init(&bufferCount, 0, 0);

    //starting scheduler
    initProcessScheduler();

    pthread_create(&processFactoryThread, NULL, processFactoryExecute, NULL);
    pthread_create(&schedulerThread, NULL, schedulerExecute, NULL);
    pthread_join(schedulerThread, NULL);

    //DEBUG ONLY!!!
    //pthread_join(processFactoryThread, NULL);
}

void initProcessScheduler(){
    //printf("-INITIALIZING SCHEDULER\n");
    //determine the number of processes
    numberOfProcess = ramdomNumber(PROCESS_NUM_MAX, PROCESS_NUM_MIN);
    //printf("--NUMBER OF PROCESS TO WORK: %d\n", numberOfProcess);
    //determine number of processes to block
    numberOfProcessToBlock = (numberOfProcess / 2);
    //printf("--NUMBER OF PROCESS TO BLOCK: %d\n", numberOfProcessToBlock);
    //printf("-SCHEDULER INITIALIZED\n");
}

/*
 * Scheduler Methods
 */
void *schedulerExecute(){
    //printf("-THREAD SCHEDULER RUNNING\n");
    int countScheduler = 0;

    for (countScheduler = 0; countScheduler < numberOfProcess; ++countScheduler) {

        //printf("--TRYING TO GET PROCESS NUMBER %d FROM BUFFER\n", countScheduler);
        while(compareBufferCount(countScheduler)){
            //printf("---STUCK\n");
        }
        Process p = getBufferedProcess(countScheduler);
        //printf("--PROCESS NUMBER %d GET\n", countScheduler);
        //printf("---EXECUTING PROCESS NUMBER %d\n",countScheduler);
        processExecute(p);
        //printf("---PROCESS NUMBER %d EXECUTED\n", countScheduler);
    }

    //get simulation end time           
    simulatorTimeInfo.endTime = getSystemTimeNow();

    showReport();
    //printf("%d PROCESSES SCHEDULED. FINISHING SCHEDULER THREAD EXECUTION\n", countScheduler);
    pthread_exit(NULL);
}

Process getBufferedProcess(int position){           
    sem_wait(&bufferMutex);
        Process p = processBufferVector[position];
    sem_post(&bufferMutex);
    return p;
}

int compareBufferCount(int position){
    int positionNow;
    sem_getvalue(&bufferCount, &positionNow);
    if(positionNow <= position){
        return 1;//fique preso
    } else {
        return 0;//se solte
    }
}

void processExecute(Process process){           
    process.startTime = getSystemTimeNow();
    printSystemTime(process.startTime);


    int time;
    int processExecTime = process.execTime;
    //printf("----PROCESS EXECUTION TIME: %d\n", processExecTime);

    if(process.gonaBlock == 1){
        int processBlockTime = process.blockTime;
        //printf("----PROCESS BLOCK TIME: %d\n", processBlockTime);

        while(processExecTime > 0 || processBlockTime > 0){
            if(processExecTime > 0){
                time = ramdomNumber(processExecTime, 1);
                //printf("-----EXECUTING TIME: %d\n", time);
                sleep(time);
                processExecTime = processExecTime - time;
            }
            if(processBlockTime > 0){
                time = ramdomNumber(processBlockTime, 1);
                //printf("-----BLOCKED TIME: %d\n", time);
                sleep(time);
                processBlockTime = processBlockTime - time;
            }
        }
    }else{
        time = processExecTime;
        //printf("-----PROCESS NOT BLOCKED. EXECUTING TIME: %d\n", time);
        sleep(time);
    }


    process.endTime = getSystemTimeNow();
    printSystemTime(process.endTime);

    process.durationTime = difftime(process.endTime, process.startTime);
}

void showReport(){
    showSimulationReport();
    printf("================================\n");
    showProcessesReport();
    printf("================================\n");
}

void showSimulationReport(){
/ * Simulator:
            a. Number of processes, OK -> numberOfProcess;
            b. Execution time in quantity;-OK> simulatorTimeInfo.startTime - simulatorTimeInfo.endTime
            c. flow;
            d. Return Time, in quantity and Average Response Time in quantity;
            f. Block Time in quantity; OK -> simulatorTimeInfo.blockTime
         * /
    double  simulationDuration  =   difftime(simulatorTimeInfo.endTime, simulatorTimeInfo.startTime);
    double  simulationOutFlow   =   numberOfProcess / simulationDuration;

    printf("#Simulation Report:\n");
    printf("- Simulation Schedule Algorithm: FIFO\n");
    printf("- Number of process: %d\n", numberOfProcess);       

    printf("- Start Time: ");
    printSystemTime(simulatorTimeInfo.startTime);

    printf("- Duration: %.1f seconds\n", simulationDuration);
    printf("- Simulation Outflow: %f process/second\n", simulationOutFlow);
    //item d
    //item e
    printf("- Total Block Time: %d seconds\n", simulatorTimeInfo.blockTime);
}

void showProcessesReport(){
/ * Each process:
            a. Start Time, OK -> process.startTime
            b. Duration quantity;
            c. End Time, OK -> process.endTime
            d. flow and Return Time in quantity;
            g. Average Response Time in quantity;
            h. Lockout Time in quantity; OK -> process.blockTime
        * /
    int processesReportCount;
    for (processesReportCount = 0; processesReportCount < numberOfProcess; ++processesReportCount) {
        Process p = processBufferVector[processesReportCount];
        double  processDuration =   p.endTime - p.startTime;

        printf("#Processes Report:\n");
        printf("- Process Number: %d\n", processesReportCount);     

        printf("-- Start Time: ");
        printSystemTime(p.startTime);

        printf("-- Duration: %.1f seconds\n", processDuration);

        printf("-- End Time: ");
        printSystemTime(p.endTime);

        //item d
        //item e
        //item g
        printf("-- Blocked Time: %d seconds\n", p.blockTime);
        printf("-- Executed Time: %d seconds\n", p.execTime);
        printf("----------------------------------------\n");
    }
}
/*
 * Process Factory Methods
 */
void *processFactoryExecute(){
    //printf("#PROCESS FACTORY RUNNING\n");
    int countProcessFactory = 0;

    for (countProcessFactory = 0; countProcessFactory < numberOfProcess; ++countProcessFactory) {
        //printf("--CREATING PROCESS NUM %d.\n", countProcessFactory);
        Process p = createProcess(countProcessFactory);
        //printf("--PROCESS NUM %d CREATED.\n", countProcessFactory);
        //printf("---ALLOCATING PROCESS NUM %d.\n", countProcessFactory);
        allocateProcess(p, countProcessFactory);
        //printf("---PROCESS NUM %d ALLOCATED.\n", countProcessFactory);
    }
    //printf("#%d PROCESSES CREATED. FINISHING FACTORY EXECUTION\n", countProcessFactory);
    pthread_exit(NULL);
}

Process createProcess(int count){
    Process process;

    process.totalTime = 0;
    process.blockTime = 0;
    process.gonaBlock = 0;

    process.totalTime = ramdomNumber(PROCESS_TIME_EXEC_MAX, PROCESS_TIME_EXEC_MIN);

    if (numberOfProcessToBlock > 0) {
        process.gonaBlock = determineProcessBlock(count);
        if (process.gonaBlock == 1) {
            if (process.totalTime < PROCESS_BLOCK_TIME_MAX) {
                process.blockTime = ramdomNumber((process.totalTime-1), PROCESS_BLOCK_TIME_MIN);
            } else {
                process.blockTime = ramdomNumber(PROCESS_BLOCK_TIME_MAX, PROCESS_BLOCK_TIME_MIN);
            }
        }
    }

    process.execTime = process.totalTime - process.blockTime;
    simulatorTimeInfo.blockTime = simulatorTimeInfo.blockTime + process.blockTime;
    return process;
}

int determineProcessBlock(int count){
    int blockF;
    if(count <= numberOfProcessToBlock){
        blockF = 1;
        numberOfProcessToBlock = numberOfProcessToBlock - 1;
    }else{
        blockF = ramdomNumber(1, 0);
        if(blockF == 1){
            numberOfProcessToBlock = numberOfProcessToBlock - 1;
        }
    }
    //printf("#PROCESSO NUM %d STATUS: %d\n", count, blockF);
    return blockF;
}

void allocateProcess(Process process, int position){
    sem_wait(&bufferMutex);
        processBufferVector[position] = process;
        sem_post(&bufferCount);
    sem_post(&bufferMutex);
}

/*
 * Util Methods
 */
int ramdomNumber(int max, int min) {
    int n;
    srand(rdtsc());
    n = ((rand() % (max - min + 1)) + min);
    return n;
}

int rdtsc() {
    __asm__ __volatile__("rdtsc");
}

time_t getSystemTimeNow(){
    return time(NULL);
}

void printSystemTime(time_t t){
    const struct tm *tm = localtime(&t);
    printf ("%04d-%02d-%02d %02d:%02d:%02d\n", tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec);

}
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
linuxunil
  • 313
  • 2
  • 14
  • 3
    Welcome to SO. Please cook your program down to a minimal example that produces your error and then try to ask a more specific question. You might also consider starting using a debugger and to step through your program to see what is happening. – Jens Gustedt Dec 19 '12 at 07:05
  • Thanks for the reply. i'm using eclipse and gdb. when i debug the code i get: process 1 start time : 2012-12-19 02:54:09 process 1 end time : 2012-12-19 02:54:20 process 2 start time : 2012-12-19 02:54:20 process 2 end time : 2012-12-19 02:54:33 process 3 start time : 2012-12-19 02:54:33 process 3 end time : 2012-12-19 02:54:49 but in the report method, it show other value. – linuxunil Dec 19 '12 at 07:17
  • side note: your `rdtsc()` implementation is wrong. See [this](http://stackoverflow.com/questions/13772567/get-cpu-cycle-count/13772771#13772771) –  Dec 19 '12 at 07:56
  • thanks for the rdtsc() note. – linuxunil Dec 19 '12 at 08:07

2 Answers2

2

The problem is in that you pass the process argument to the processExecute by value. This means that inside the processExecute function the process variable is like any other local variable, and the lifetime of the variable is the lifetime of the function. So any changes to the structure will not be passed in up.

You need to pass the Process structure by reference, by using pointers:

void processExecute(Process *process){
    process->startTime = getSystemTimeNow();

    /* ... */
}

This means a redesign of your program as you only pass the Process structure around as values (which means they are only copies) in more places.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • thanks for the reply. I was suspecting that. Somewhere in my code should there be a failure in the lifetime of variables. Thanks for pointing out! Once I have time I will be modifying the code. – linuxunil Dec 19 '12 at 13:02
0

Your code is too long to read throughly. Is the time being set on a different thread? Stack isn't shared as far as I know, so I expect what you set on one thread is not visible on the other. Allocate on the heap to avoid this.

Karthik T
  • 31,456
  • 5
  • 68
  • 87
  • There are two threads in my program. 1 - Process factory: it creates Process type structures and places in processBufferVector [PROCESS_NUM_MAX]; 2 - Scheduler: it removes Process type structures from processBufferVector[PROCESS_NUM_MAX]. The start and end times for the processes are being obtained in this thread. So, i don't think this is the problem. – linuxunil Dec 19 '12 at 07:07