Skip to content

Commit

Permalink
framework: add try lock times to reduce possible lock failure
Browse files Browse the repository at this point in the history
  • Loading branch information
zhongjunni authored and Jiangtao Hu committed Dec 13, 2018
1 parent 2c2e523 commit 2441485
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
21 changes: 16 additions & 5 deletions cyber/transport/shm/block.cc
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ namespace transport {

const int32_t Block::kRWLockFree = 0;
const int32_t Block::kWriteExclusive = -1;
const int32_t Block::kMaxTryLockTimes = 5;

Block::Block() : msg_size_(0), msg_info_size_(0) {}

Expand All @@ -47,11 +48,21 @@ bool Block::TryLockForRead() {
return false;
}

if (!lock_num_.compare_exchange_weak(lock_num, lock_num + 1,
std::memory_order_acq_rel,
std::memory_order_relaxed)) {
AINFO << "fail to add read lock num, curr num: " << lock_num;
return false;
int32_t try_times = 0;
while (!lock_num_.compare_exchange_weak(lock_num, lock_num + 1,
std::memory_order_acq_rel,
std::memory_order_relaxed)) {
++try_times;
if (try_times == kMaxTryLockTimes) {
AINFO << "fail to add read lock num, curr num: " << lock_num;
return false;
}

lock_num = lock_num_.load();
if (lock_num < kRWLockFree) {
AINFO << "block is being written.";
return false;
}
}

return true;
Expand Down
1 change: 1 addition & 0 deletions cyber/transport/shm/block.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ class Block {

static const int32_t kRWLockFree;
static const int32_t kWriteExclusive;
static const int32_t kMaxTryLockTimes;

private:
bool TryLockForWrite();
Expand Down

0 comments on commit 2441485

Please sign in to comment.