c++ - Try-lock semaphore using standard libraries -
i'm building sokoban solver. since i'm doing depth-first search (yes, horrible idea, know) wish multithreaded.
my function recursive. therefore semaphore (like suggested here), need able attempt lock, , in case of no lock-ability proceed if nothing happened.
the semaphores supposed control whether or not new thread should initiated. since using recursive function can imagine whole lot of overhead, implement linked semaphore , wait release.
so: how try lock semaphore, skip waiting if no more semaphores available? or there better solution semaphores?
my build chain supports c++14. have boost installed, avoid third party libraries. using ubuntu 14.04.
(when have done want this, i'll have go @ ida*, focus on want achieve rather solving underlying enormous problem approach solving sokoban puzzle :-) )
so have add new method semaphore
class (try
)
// boost needed no more #include <condition_variable> #include <mutex> using namespace std; class semaphore { private: mutex mutex_; condition_variable condition_; unsigned long count_; public: semaphore() : count_() {} void notify() { unique_lock<mutex> lock(mutex_); ++count_; condition_.notify_one(); } void wait() { unique_lock<mutex> lock(mutex_); while(!count_) condition_.wait(lock); --count_; } bool try() { unique_lock<mutex> lock(mutex_); if (count_) { --count_; return true; } else { return false; } } };
Comments
Post a Comment