Linux Processor Spinning C++

Discussion in 'General Programming Support' started by Dan, Jun 23, 2015.

  1. Dan

    Dan The New Helper.Net gives me great Anxiety... o.O;;

    Ratings:
    +160 / 1 / -0
    Hey guys, I'm coming to you because I love you.

    I am working on a project in C++ and I was wondering if anyone knew how Linux handles sharing the processor as a resource across threads. Essentially, I have multiple threads that are going to be waiting for a flag to change. A colleague of mine said that a while loop waiting on a duration of time to pass might cause "spinning" to occur and make threads fight for resources.

    My colleague wrote the original code-base for the project I'm porting over to Linux. It was an embedded system that uses something called Keil OS, so it handles threads and deals with Interrupt Scheduling.

    Thoughts?
     
  2. Slapshot136

    Slapshot136 Divide et impera

    Ratings:
    +483 / 2 / -0
    Normally there is an implementation to notify threads such that you don't need to wait a specified amount of time like mutex and semaphore - as long as there is some wait though, it shouldn't be too bad of a spin , assuming you mean CPU resources and a reasonable number of threads (say under 100) - if you need access to other stuff (static instances, etc.) then you need to be even more careful about locks to avoid stuff like the dining philosophers issue - not an expert but in linux/c++ environments I believe it's usually done via pthread and the related functions

    as far as the actual CPU time scheduling and time-slicing, those still vary a ton depending on the OS/CPU itself, but I wouldn't really worry too much about that unless your 100% sure of what your platform will be AND have a reason to optimize further (premature optimization is the root of all evil)
     
    Last edited: Jun 23, 2015
  3. Accname

    Accname 2D-Graphics enthusiast

    Ratings:
    +1,551 / 4 / -4
    Really depends on how long you want to wait. If its rather short (below seconds) then busy-waiting (while loop) is okay. If its longer you should send your thread to sleep and check regularily. If its a little bit longer but not too long you could yield CPU ownership.
    A yield means that your thread gives up the CPU if the CPU is requested by another thread. If the CPU has nothing better to do your thread will keep it. Sleeping is forced and will block your thread until interrupted by the OS (after a certain time for example).

    Something like this (in pseudo code):
    Code:
    loop {
        if (condition is met?) {
            break loop
        }
        yield // or sleep(100 millis)
    }
     

Share This Page