Apollo 10.0
自动驾驶开放平台
block.cc
浏览该文件的文档.
1/******************************************************************************
2 * Copyright 2018 The Apollo Authors. All Rights Reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *****************************************************************************/
16
18
19#include "cyber/common/log.h"
20
21namespace apollo {
22namespace cyber {
23namespace transport {
24
25const int32_t Block::kRWLockFree = 0;
26const int32_t Block::kWriteExclusive = -1;
27const int32_t Block::kMaxTryLockTimes = 5;
28
29Block::Block() : msg_size_(0), msg_info_size_(0) {}
30
32
33bool Block::TryLockForWrite() {
34 int32_t rw_lock_free = kRWLockFree;
35 if (!lock_num_.compare_exchange_weak(rw_lock_free, kWriteExclusive,
36 std::memory_order_acq_rel,
37 std::memory_order_relaxed)) {
38 ADEBUG << "lock num: " << lock_num_.load();
39 return false;
40 }
41 return true;
42}
43
44bool Block::TryLockForRead() {
45 int32_t lock_num = lock_num_.load();
46 if (lock_num < kRWLockFree) {
47 AINFO << "block is being written.";
48 return false;
49 }
50
51 int32_t try_times = 0;
52 while (!lock_num_.compare_exchange_weak(lock_num, lock_num + 1,
53 std::memory_order_acq_rel,
54 std::memory_order_relaxed)) {
55 ++try_times;
56 if (try_times == kMaxTryLockTimes) {
57 AINFO << "fail to add read lock num, curr num: " << lock_num;
58 return false;
59 }
60
61 lock_num = lock_num_.load();
62 if (lock_num < kRWLockFree) {
63 AINFO << "block is being written.";
64 return false;
65 }
66 }
67
68 return true;
69}
70
71void Block::ReleaseWriteLock() { lock_num_.fetch_add(1); }
72
73void Block::ReleaseReadLock() { lock_num_.fetch_sub(1); }
74
75} // namespace transport
76} // namespace cyber
77} // namespace apollo
static const int32_t kRWLockFree
Definition block.h:42
static const int32_t kWriteExclusive
Definition block.h:43
static const int32_t kMaxTryLockTimes
Definition block.h:44
#define ADEBUG
Definition log.h:41
#define AINFO
Definition log.h:42
class register implement
Definition arena_queue.h:37