Like Tree1Likes
  • 1 Post By MK27

elevator simulation problem - clock thread

This is a discussion on elevator simulation problem - clock thread within the C Programming forums, part of the General Programming Boards category; hello, i am working on implementing the elevator simulation problem in C for my assign. Here we have to deal ...

  1. #1
    Registered User
    Join Date
    Jan 2012
    Posts
    38

    elevator simulation problem - clock thread

    hello, i am working on implementing the elevator simulation problem in C for my assign. Here we have to deal wit a clock thread, thread for each work in the building and a monitor structure to manage the elevator. I am trying to figure how to keep track of everything, hence trying to understand how to implement multithreading properly.

    my first step was to make the elevator work with only the clock thread, but i dont know if my approach is right. this is what i am doing...can u let me know if my approach is correct...i think u can help students out by telling if there approach is atleast correct

    my clock thread will be responsible for checking the current position of the elevator. if it is on the ground floor it will go up, if it is on the top floor it will go down. if it is somewhere in between, based on a random value it will either go up or down. what i dont get ism will my clock thread keep track of actual time or i can setup my own clock which initializes whenever i run my program and keep track of where the elevator is after each clock period?

    also, since for now, i only have a clock thread, do i need to take care of any synchornzation issues?? or do we handle them when we bring the people threads into the code?

    hope to hear from u soon!!

  2. #2
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    It's not totally clear what you are doing. I googled "the elevator problem":

    Programming Challenge 3 - Controlling Elevators in a Building
    The Elevator Problem

    And IMO it is not a task that calls for multi-threading. Keep in mind that
    a) the system clock runs independent of your program, and you can access that -- you don't need something to keep time independently.
    b) the measurement of "time" in this problem seems more about relationships, and real time may not be relevant to it.

    But, if you have been told to do this with threads...

    Quote Originally Posted by ueg1990 View Post
    also, since for now, i only have a clock thread, do i need to take care of any synchornzation issues?? or do we handle them when we bring the people threads into the code?
    Any variable which will be accessed -- for reading or writing -- by more than one thread requires some method of synchronization.

    Finally, when in doubt, post code. Simply describing what you think your code does or should do is too abstract.
    Salem likes this.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  3. #3
    Registered User
    Join Date
    Jan 2012
    Posts
    38
    this is the code i wrote uptill now, when i created by clock thread, it does not call the function i want it to call:
    Code:
    #include<stdio.h>
    #include<string.h>
    #include<stdlib.h>
    #include<pthread.h>
    #include<unistd.h>
    
    #define UP 0
    
    #define DOWN 1
    
    void* initialize(int);
    void* clock_thread(void*);
    int  go_up(int,int);
    int  go_down(int);
    
    typedef struct{
        int direction,up,down,position,busy, num_of_floors;
        pthread_mutex_t mutex;
        pthread_cond_t upsweep,downsweep;
    }MonitorElevator;
    
    int clock_var;
    //int position;
    int pos;
    
    int main(int argc, char* argv[]){
        MonitorElevator* mon_elev;
        pthread_mutex_t mutex;
        int num_of_floors;
        pos=0;
        pthread_t thread_clock_id;
    
    
        if(argc !=2){
            fprintf(stderr,"usage: ./ue number_of_floors\n");
            exit(1);
        }
        num_of_floors = atoi(argv[1]);
        printf("The number of floors in the building is %d\n",num_of_floors);
        initialize(num_of_floors);
        pthread_mutex_init(&mutex,NULL);
    
        mon_elev->position=pos;
        mon_elev->num_of_floors = num_of_floors;
        pthread_create(&thread_clock_id,NULL,&clock_thread,(void*)pos);
        printf("Thread created\n");
    
    }
    
    void*     initialize(int num_of_floors){
        MonitorElevator* mon_elev;
        mon_elev = (MonitorElevator*)malloc(sizeof(MonitorElevator));
        mon_elev->num_of_floors = num_of_floors;
        mon_elev->direction =1;
        mon_elev->up = UP;
        mon_elev->down = DOWN;
        mon_elev->position = 0;
        mon_elev->busy = 0;
        pthread_mutex_init(&mon_elev->mutex,NULL);
        pthread_cond_init(&mon_elev->upsweep,NULL);
        pthread_cond_init(&mon_elev->downsweep,NULL);
        clock_var=0;
    
    }
    
    void* clock_thread(void* v){
        printf("Inside clock thread\n");
        fflush(stdout);
        int position = *((int*)v);
        MonitorElevator* mon_elev;
        int num_of_floors,direction;
        num_of_floors = mon_elev->num_of_floors;
    
        while(1){
            pthread_mutex_lock(&mon_elev->mutex);
            if(position ==0){
                printf("At the ground floor (%d)\nElevator going up.....\n",position);
                fflush(stdout);
                    go_up(position,num_of_floors);            
            }
            else if(position == num_of_floors){
                printf("At the top floor(%dth)\nElevator going down.....\n",position);
                fflush(stdout);
                go_down(position);
            }
            else {
                printf("At the %dth floor\n",position);
                fflush(stdout);
                if((direction=(rand()%2))==UP){
                    printf("Elevator is going up\n");
                    fflush(stdout);
                    go_up(position,num_of_floors);
                }
                else {
                    printf("Elevator is going down\n");
                    fflush(stdout);
                    go_down(position);
                }
            }
            pthread_mutex_unlock(&mon_elev->mutex);
        }
    }
    
    int go_up(int position,int num_of_floors){
        
        if(position<num_of_floors){
            sleep(1);
            position++;
            printf("Now at the %dth floor\n",position);
            fflush(stdout);
            return position;
        }
    }
    
    int go_down(int position)
        if(position>0){
            sleep(1);
            position--;
            printf("Now at the %dth floor\n",position);
            fflush(stdout);
            return position;
        }
    }

  4. #4
    spurious conceit MK27's Avatar
    Join Date
    Jul 2008
    Location
    segmentation fault
    Posts
    8,300
    You're trying to bite off more than you can chew for the moment. You would be much better off, and save yourself more time in the long run, if you do some simple exercises or experiments with the pthreads API before you try and apply it here.

    The reason the clock thread does not seem to fire is because POSIX threads by default begin detached. That is most likely what you want, however, when the parent thread terminates, so do all its children, detached or not. This create call:

    Code:
        pthread_create(&thread_clock_id,NULL,&clock_thread,(void*)pos);
    Does create a thread, but the OS scheduler determines when that thread first executes. Remember, multi-threading does not necessarily (or even, in general) mean that two threads literally happen simultaneously. That is possible on a multi-core system, but the significance of it is limited because, eg, no matter how many cores and threads you have, only one thread at a time can access a specific disk, or a specific input/output stream (such as the console). The scheduler is responsible for alternating them, and one reason to de-schedule a thread is because it is waiting on I/O.

    Short of a distinct reason to stop, in general, a thread runs for an indeterminate period of time (measurable in milliseconds, say), then gets swapped for another. Thinking of building two block piles with one hand, alternating between them so they more or less are piled up concurrently. Here's a block of code;

    Code:
        mon_elev->position=pos;
        mon_elev->num_of_floors = num_of_floors;
        pthread_create(&thread_clock_id,NULL,&clock_thread,(void*)pos);
        printf("Thread created\n");
    
    }
    That's your main(), and represents the parent thread. Most likely, this will run all at once, unless, by some small chance, the scheduler swaps it out, eg, after the create call. Otherwise, that run will include the termination of the program (main is done!), which does not require detached threads to be in any particular state -- they are destroyed in whatever at that point (if one is running on another processor, it will complete whatever time it has there), and never get scheduled again. The program is over. This is different than using fork(). There is only one process in the eyes of the OS.

    So, if you throw a sleep() in immediately after the create(), you'll get:

    root~/C./a.out 666
    The number of floors in the building is 666
    Inside clock thread
    Segmentation fault


    Because sleep() will de-schedule the calling thread, and the clock thread gets a chance (most likely) to do something. Can't say what the seg fault is at this point, lol, tho. Like I said, I think you should rip a lot of this out for now or write something simpler and separate to get the hang of pthreads. It will also probably help you later to have a simplified model to play around with.

    Note that I used sleep() here just to illustrate something. DO NOT USE SLEEP or some other timer to synchronize threads; it a) usually defeats the purpose of multi-threading, b) cannot be guaranteed to work and hence c) indicates a design flaw.
    Last edited by MK27; 02-22-2012 at 11:44 AM.
    C programming resources:
    GNU C Function and Macro Index -- glibc reference manual
    The C Book -- nice online learner guide
    Current ISO draft standard
    CCAN -- new CPAN like open source library repository
    3 (different) GNU debugger tutorials: #1 -- #2 -- #3
    cpwiki -- our wiki on sourceforge

  5. #5
    - - - - - - - - oogabooga's Avatar
    Join Date
    Jan 2008
    Posts
    2,808
    Another point is that a simulation of this kind is not normally implemented in real time! Instead you would generate events (randomly or read from a file) and just jump ahead to the times when something actually happens.

    Could you explain exactly what you're trying to simulate here? A link to the actual assignment might help.

  6. #6
    Registered User Codeplug's Avatar
    Join Date
    Mar 2003
    Posts
    4,607
    >> ... POSIX threads by default begin detached.
    Actually, the default state is joinable. pthread_attr_getdetachstate

    gg

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. clock() problem
    By hugoguan in forum C Programming
    Replies: 8
    Last Post: 11-23-2010, 12:54 PM
  2. clock() problem
    By Nick_3596 in forum C Programming
    Replies: 5
    Last Post: 11-29-2007, 02:26 AM
  3. Cross Stitching Simulation Problem
    By gnome in forum C Programming
    Replies: 2
    Last Post: 10-25-2005, 12:48 PM
  4. Simulation Problem
    By wu_weidong in forum C Programming
    Replies: 1
    Last Post: 03-10-2005, 12:21 AM
  5. 1, 2, 3, 4 take the elevator
    By iain in forum A Brief History of Cprogramming.com
    Replies: 13
    Last Post: 10-14-2002, 09:51 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21