Joshua
open source statistical hierarchical phrase-based machine translation system
 All Classes Namespaces Functions Variables Typedefs Enumerations Enumerator Friends
src/kenlm/util/stream/multi_progress.hh
00001 /* Progress bar suitable for chains of workers */
00002 #ifndef UTIL_STREAM_MULTI_PROGRESS_H
00003 #define UTIL_STREAM_MULTI_PROGRESS_H
00004 
00005 #include <boost/thread/mutex.hpp>
00006 
00007 #include <cstddef>
00008 #include <stdint.h>
00009 
00010 namespace util { namespace stream {
00011 
00012 class WorkerProgress;
00013 
00014 class MultiProgress {
00015   public:
00016     static const unsigned char kWidth = 100;
00017 
00018     MultiProgress();
00019 
00020     ~MultiProgress();
00021 
00022     // Turns on showing (requires SetTarget too).
00023     void Activate();
00024 
00025     void SetTarget(uint64_t complete);
00026 
00027     WorkerProgress Add();
00028 
00029     void Finished();
00030 
00031   private:
00032     friend class WorkerProgress;
00033     void Milestone(WorkerProgress &worker);
00034 
00035     bool active_;
00036 
00037     uint64_t complete_;
00038 
00039     boost::mutex mutex_;
00040 
00041     // \0 at the end.
00042     char display_[kWidth + 1];
00043 
00044     std::size_t character_handout_;
00045 
00046     MultiProgress(const MultiProgress &);
00047     MultiProgress &operator=(const MultiProgress &);
00048 };
00049 
00050 class WorkerProgress {
00051   public:
00052     // Default contrutor must be initialized with operator= later.
00053     WorkerProgress() : parent_(NULL) {}
00054 
00055     // Not threadsafe for the same worker by default.
00056     WorkerProgress &operator++() {
00057       if (++current_ >= next_) {
00058         parent_->Milestone(*this);
00059       }
00060       return *this;
00061     }
00062 
00063     WorkerProgress &operator+=(uint64_t amount) {
00064       current_ += amount;
00065       if (current_ >= next_) {
00066         parent_->Milestone(*this);
00067       }
00068       return *this;
00069     }
00070 
00071   private:
00072     friend class MultiProgress;
00073     WorkerProgress(uint64_t next, MultiProgress &parent, char character)
00074       : current_(0), next_(next), parent_(&parent), stone_(0), character_(character) {}
00075 
00076     uint64_t current_, next_;
00077 
00078     MultiProgress *parent_;
00079 
00080     // Previous milestone reached.
00081     unsigned char stone_;
00082 
00083     // Character to display in bar.
00084     char character_;
00085 };
00086 
00087 }} // namespaces
00088 
00089 #endif // UTIL_STREAM_MULTI_PROGRESS_H