Skip to content

Commit

Permalink
add tryLockMember
Browse files Browse the repository at this point in the history
  • Loading branch information
ESResearchDepartment committed Jul 25, 2024
1 parent 9034af6 commit 2ea3cfe
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
7 changes: 7 additions & 0 deletions include/libgeneral/GuardAccess.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ namespace tihmstar {
void lockMember();
void unlockMember();

/*
Attempts to lock Member if it is not already locked.
Returns true if lock was acquired
Returns false if already locked
*/
bool tryLockMember();

//block until someone removed members
void waitForMemberDrain();
};
Expand Down
20 changes: 18 additions & 2 deletions libgeneral/GuardAccess.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,11 @@ GuardAccess::~GuardAccess(){
#pragma mark public
void GuardAccess::addMember(){
while (true){
if (_members.fetch_add(1) >= GuardAccess::maxMembers){
if (_members.fetch_add(1) >= GuardAccess::maxMembers-1){
_members.fetch_sub(1); _leaveEvent.notifyAll();

uint64_t wevent = _leaveEvent.getNextEvent();
while (_members>=GuardAccess::maxMembers){
while (_members>=GuardAccess::maxMembers-1){
_leaveEvent.waitForEvent(wevent);
wevent = _leaveEvent.getNextEvent();
}
Expand Down Expand Up @@ -73,6 +73,22 @@ void GuardAccess::unlockMember(){
_leaveEvent.notifyAll();
}

bool GuardAccess::tryLockMember(){
while (true){
if (_members.fetch_add(GuardAccess::maxMembers) >= GuardAccess::maxMembers){
_members.fetch_sub(GuardAccess::maxMembers); _leaveEvent.notifyAll();
return false;
}else{
uint64_t wevent = _leaveEvent.getNextEvent();
while (_members > GuardAccess::maxMembers){
_leaveEvent.waitForEvent(wevent);
wevent = _leaveEvent.getNextEvent();
}
return true;
}
}
}

void GuardAccess::waitForMemberDrain(){
uint64_t wevent = _leaveEvent.getNextEvent();
_leaveEvent.waitForEvent(wevent);
Expand Down

0 comments on commit 2ea3cfe

Please sign in to comment.