2 * Copyright (C) 2017 Cisco Inc.
4 * This program is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License, version 2,
6 * as published by the Free Software Foundation.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License
14 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 // @author Changxue Deng <chadeng@cisco.com>
19 #ifndef __LOCK_FREE_H__
20 #define __LOCK_FREE_H__
30 // C++11 std::atomic shared memory variable for lock-free
31 // reader/writer concurrency.
33 #define MAX_OFFSET_CACHE 4
34 #define MEMORY_ORDER_WRITER std::memory_order_release
35 #define MEMORY_ORDER_READER std::memory_order_consume
38 typedef struct _IndexHeader IndexHeader;
40 typedef struct _LockFreeData
46 typedef struct _LockFreeShmData
48 std::atomic<uint32_t> counter;
49 std::atomic<size_t> offset;
50 std::atomic<size_t> offset_cache[MAX_OFFSET_CACHE];
59 void LockFreeInit(LockFreeShmData *lock_free_ptr, IndexHeader *hdr, int mode = 0);
60 inline void WriterLockFreeStart(size_t offset);
61 void WriterLockFreeStop();
62 inline void ReaderLockFreeStart(LockFreeData &snapshot);
63 // If there was race condition, this function returns MBError::TRY_AGAIN.
64 int ReaderLockFreeStop(const LockFreeData &snapshot, size_t reader_offset,
68 LockFreeShmData *shm_data_ptr;
69 const IndexHeader *header;
72 inline void LockFree::WriterLockFreeStart(size_t offset)
74 shm_data_ptr->offset.store(offset, MEMORY_ORDER_WRITER);
77 inline void LockFree::ReaderLockFreeStart(LockFreeData &snapshot)
79 snapshot.counter = shm_data_ptr->counter.load(MEMORY_ORDER_READER);