Click here to Skip to main content
15,891,184 members
Articles / General Programming / Threads

Lock-Free Single-Producer - Single Consumer Circular Queue

Rate me:
Please Sign up or sign in to vote.
4.84/5 (58 votes)
31 Dec 2014Public Domain20 min read 428.1K   5.5K   195  
How to make a wait-free, lock-free CircularFifo using C++11.
#ifndef G2_CHRONO_H_ 
#define G2_CHRONO_H_

// http://kjellkod.wordpress.com/2012/02/06/exploring-c11-part-1-time/#more-458
#include <iostream>
#include <chrono>
#include <thread>


namespace g2
{       
  typedef std::chrono::high_resolution_clock clock;
  typedef std::chrono::microseconds microseconds;
  typedef std::chrono::milliseconds milliseconds;

  clock::time_point now(){return clock::now();}

  microseconds intervalUs(const clock::time_point& t1, const clock::time_point& t0)
  {return std::chrono::duration_cast<microseconds>(t1 - t0);}

  milliseconds intervalMs(const clock::time_point& t1,const clock::time_point& t0)
  {return std::chrono::duration_cast<milliseconds>(t1 - t0);}


  template<typename Duration>
  void short_sleep(Duration d) // thanks to Anthony Williams for the suggestion of short_sleep
  {                            
    clock::time_point const start=clock::now(), stop=start+d;
    do{
      std::this_thread::yield();
    } while(clock::now()<stop);
  }

  class StopWatch
  {
    clock::time_point start_;
  public:
    StopWatch() : start_(clock::now()){}
    clock::time_point restart()         { start_ = clock::now(); return start_;}
    microseconds elapsedUs()            { return intervalUs(now(), start_);}
    milliseconds elapsedMs()            {return intervalMs(now(), start_);}
  };
} // g2



#endif // G2_CHRONO_H_

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under A Public Domain dedication


Written By
Software Developer (Senior) LogRhythm
United States United States
Enjoying Colorado! Family and intense software development.

Kjell is a driven developer with a passion for software development. His focus is on coding, boosting software development, improving development efficiency and turning bad projects into good projects.

Kjell was twice national champion in WUKO and semi-contact Karate and now he focuses his kime towards software engineering, everyday challenges and moose hunting while not being (almost constantly) amazed by his daughter and sons.

Comments and Discussions