semaphores using C++ in console program

This is a discussion on semaphores using C++ in console program within the C++ Programming forums, part of the General Programming Boards category; On another baorad I've been following an interesting discussion regarding semaphores to protect a critical section of code in a ...

  1. #1
    Unregistered
    Guest

    semaphores using C++ in console program

    On another baorad I've been following an interesting discussion regarding semaphores to protect a critical section of code in a multithreaded program using standard C++ in console mode. The only system call allowed is CreateThread(). Anybody here familiar with the topic? Anybody have an example of the use of a semaphore outside of the API functions, or have knowledge of the code underlying the API functions dealing with semaphores, or websites I might check for same?

  2. #2
    Super Moderator
    Join Date
    Sep 2001
    Posts
    4,913

    If you consider ships outside of the API...

    Semaphore is a language used with flags between ships. Like a really big sign language. How does that tie into programming? I'd like to know!

  3. #3
    Registered User cody's Avatar
    Join Date
    Sep 2001
    Posts
    86
    Heyho

    Yes, semaphores are used/needed when you want several threads to access the same variable(s) safely. Imagine the situation that you have an input buffer you want to read out continously with one thread, while another thread fills it with new input from e.g. the serial port or something like that.

    While the read-thread is reading out the buffer, there might already be new incoming input at the serial port. Without semaphores you'd maybe lose some of the incoming data or witness any other strange behavior of your program

    So a semaphore is something like a 'traffic light' if you want to make it really simple Before a thread can access the 'dangerous' variables/functions it has to obtain the semaphore first. Once it has obtained the semaphore it switches the semaphore status to "OK guys, it's my turn now!" Now the 'traffic light' is red and another thread will have to wait until the first thread releases the semaphore again to signal that it is done with whatever it wanted to do.

    When the first thread releases the semaphore, it switches the semaphore's status back to "Freeeeeedom" Now the other thread has the chance to obtain the semaphore and perform some actions...

    In Windows/MSVC++ you might want to check the :

    - CreateSemaphore ()
    - WaitForSingleObject ()
    - ReleaseSemaphore ()

    functions. They are used to create, obtain and release a semaphore under Windows. It's a little bit different in Linux, but the idea is basicly the same.

    Hope that helps
    aloa
    cody
    Last edited by cody; 12-19-2001 at 03:01 AM.
    #include "reallife.h"

  4. #4
    ....
    Join Date
    Aug 2001
    Location
    Groningen (NL)
    Posts
    2,386
    Imagine we have the two parallel functions.

    function1
    {
    get (A);
    get (B);
    X = A + B;
    print (X);
    }

    function2
    {
    get (C);
    get (D);
    X = C + D;
    print (X);
    }

    Imagine that both function1 and function2 have retrieved their parameters. Now they want to calculate the sum of the parameters and print the result.

    Now function1 performs the calculation and stores the value (A+B) into X. Then function2 performs the calculation and stores the value (C+D) into X. After that function2 did that, function1 prints X. Instead of printing (A+B), it will print (C+D).

    The reason that this happens is that function2 was allowed to modify variable X while function1 was using it. To prevent function2 from using variable X, a semaphore will be made high by function1. And it will be made low again when function1 doesn't need X anymore.

    In pseude code it looks like something like this. The code between the semaphore operations is called the critical section.

    function1
    {
    get (A);
    get (B);

    /* If the semaphore is HIGH, then this means that function2 is
    using X and function1 must wait. If the semaphore is LOW,
    then make the semaphore high and function1 can use the
    variable X. */
    wait (semaphore);

    /* Critical section */
    X = A + B;
    print (X);

    /* Variable X isn't needed anymore. Make semaphore LOW so
    that function2 can use it. */
    release (semaphore);
    }

  5. #5
    It's full of stars adrianxw's Avatar
    Join Date
    Aug 2001
    Posts
    4,831
    >>> CreateThread().

    This is not generally a good API function to call. Use _beginthread() or _beginthreadex() as they are less prone to creating code with memory leaks.

    You've seen some ideas. Remember though, true semaphores work at a lower level than "in application" semaphores since a context switch can occur at any time.
    Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream.

  6. #6
    Unregistered
    Guest
    Indeed it is the low level stuff that have formed the basis of the discussion/puzzle. You are allowed no API call other than the call(s) to create the thread(s) (CreateThread or _beginthread at your discretion). This code is to be done uing C++ in Console/DOS mode, NOT Windows. The problem revolves around creating your own semaphore lock (rather than relying on the ones in the API) and developing a mechanism to prevent thread starvation. Very low-level stuff. Interesting and frustrating simultaneously. I have scanned the internet and looked at websites suggested on previous posts here, but I have yet to find anything useful except information indicating need for a lock/unlock mechanism and a queueing mechanism to prevent starvation, but no actual source code to back it up.

    The person posing the problem/puzzle indicates they will post their solution soon, as, so far, no one has posted code that meets all the criteria. Thanks for the input.

  7. #7
    It's full of stars adrianxw's Avatar
    Join Date
    Aug 2001
    Posts
    4,831
    >>> Console/DOS mode, NOT Windows

    Remember - a console is a Window. A console app is treated the same as any other Win32 app by the OS.

    Your threads are going to be scheduled by Windows. If you can't use any other API functions then the thread creators, there is nothing you can do about that. You can't set the priorities, suspend or activate, nothing.

    So each thread needs to run a loop where it checks some global variable to see if it can do something, the semaphore. If the semaphore is available, so grab it, and do your job, if not keep looping until it is available.

    I know very little about what it is you are trying to do. Perhaps you should have some kind of in app thread priority mechanism whereby a thread that has recently had the semaphore drops it's priority, one that has not had it for some time raises it own. Then when a thread gets the semaphore, it can check to see if any other threads have a higher priority, and if so, release the semaphore without doing any work.
    Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream.

  8. #8
    Unregistered
    Guest
    Your analysis of the problem is on target. Your algorhythm is exactly what the responders have been trying to do, without success to date, according to the moderator. The problem seems to be implementing the various tasks (basically as you have listed them, although, to date, no one has brought priority into play--instead the approach has been to use a queue to assure that only one thread is active at a time, but each thread has been given same priority) so each step is atomic, or if not atomic, acts as if it were. The program itself is frivolous, each thread enters an unending loop that increments and displays values in a global array. If all goes well there is just a series of numbers displayed to the screen documenting that the array is being updated appropriately, and that the threads are all being allowed to each do their thing, in their turn. I'm sure I'll learn something when the answer is posted, either by the moderator or a responder.

  9. #9
    It's full of stars adrianxw's Avatar
    Join Date
    Aug 2001
    Posts
    4,831
    >>>
    the approach has been to use a queue to assure that only one thread is active at a time,
    <<<

    But that is not the case. If you cannot use API functions, you cannot decide from another part of your program, which thread can run, it is Windows that is your scheduler. What you need to do is have each of your threads act as a simple state machine. This is fiddly coding, but not difficult. Where is this competition, and what are the prizes.....? <fx> rubs hands together and is already spending the prize money!</fx>
    Wave upon wave of demented avengers march cheerfully out of obscurity unto the dream.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Intergrating console program into windowed app
    By spadez in forum C Programming
    Replies: 4
    Last Post: 02-26-2009, 12:58 PM
  2. Client-server system with input from separate program
    By robot-ic in forum Networking/Device Communication
    Replies: 3
    Last Post: 01-16-2009, 03:30 PM
  3. How to avoid console program crash when terminated too early
    By Xargo in forum A Brief History of Cprogramming.com
    Replies: 6
    Last Post: 10-03-2007, 05:43 PM
  4. Replies: 2
    Last Post: 05-10-2002, 05:16 PM
  5. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 11:04 PM

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