Changeset View
Changeset View
Standalone View
Standalone View
src/sync.h
Show First 20 Lines • Show All 199 Lines • ▼ Show 20 Lines | |||||
class CSemaphore { | class CSemaphore { | ||||
private: | private: | ||||
std::condition_variable condition; | std::condition_variable condition; | ||||
std::mutex mutex; | std::mutex mutex; | ||||
int value; | int value; | ||||
public: | public: | ||||
CSemaphore(int init) : value(init) {} | explicit CSemaphore(int init) : value(init) {} | ||||
void wait() { | void wait() { | ||||
std::unique_lock<std::mutex> lock(mutex); | std::unique_lock<std::mutex> lock(mutex); | ||||
condition.wait(lock, [&]() { return value >= 1; }); | condition.wait(lock, [&]() { return value >= 1; }); | ||||
value--; | value--; | ||||
} | } | ||||
bool try_wait() { | bool try_wait() { | ||||
▲ Show 20 Lines • Show All 42 Lines • ▼ Show 20 Lines | void MoveTo(CSemaphoreGrant &grant) { | ||||
grant.Release(); | grant.Release(); | ||||
grant.sem = sem; | grant.sem = sem; | ||||
grant.fHaveGrant = fHaveGrant; | grant.fHaveGrant = fHaveGrant; | ||||
fHaveGrant = false; | fHaveGrant = false; | ||||
} | } | ||||
CSemaphoreGrant() : sem(nullptr), fHaveGrant(false) {} | CSemaphoreGrant() : sem(nullptr), fHaveGrant(false) {} | ||||
CSemaphoreGrant(CSemaphore &sema, bool fTry = false) | explicit CSemaphoreGrant(CSemaphore &sema, bool fTry = false) | ||||
: sem(&sema), fHaveGrant(false) { | : sem(&sema), fHaveGrant(false) { | ||||
if (fTry) | if (fTry) | ||||
TryAcquire(); | TryAcquire(); | ||||
else | else | ||||
Acquire(); | Acquire(); | ||||
} | } | ||||
~CSemaphoreGrant() { Release(); } | ~CSemaphoreGrant() { Release(); } | ||||
operator bool() { return fHaveGrant; } | operator bool() const { return fHaveGrant; } | ||||
}; | }; | ||||
#endif // BITCOIN_SYNC_H | #endif // BITCOIN_SYNC_H |