anjana_sreekumar@infosys.com | 991c206 | 2020-01-08 11:42:57 +0530 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (c) 2019, Infosys Ltd. |
| 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 | |
| 17 | #ifndef INCLUDE_CMN_BLOCKINGCIRCULARFIFO_H_ |
| 18 | #define INCLUDE_CMN_BLOCKINGCIRCULARFIFO_H_ |
| 19 | |
| 20 | #include <cstddef> |
| 21 | #include <semaphore.h> |
| 22 | #include "circularFifo.h" |
| 23 | |
| 24 | namespace cmn { |
| 25 | namespace utils { |
| 26 | |
| 27 | template<typename Element, size_t size> |
| 28 | class BlockingCircularFifo |
| 29 | { |
| 30 | public: |
| 31 | BlockingCircularFifo():circularQueue() |
| 32 | { |
| 33 | sem_init(&pop_semaphore, 0, 0); |
| 34 | sem_init(&push_semaphore, 0, size); |
| 35 | } |
| 36 | |
| 37 | ~BlockingCircularFifo() |
| 38 | { |
| 39 | sem_destroy(&pop_semaphore); |
| 40 | sem_destroy(&push_semaphore); |
| 41 | } |
| 42 | |
| 43 | bool push(Element* item) |
| 44 | { |
| 45 | sem_wait(&push_semaphore); |
| 46 | bool ret = circularQueue.push(item); |
| 47 | if (ret) |
| 48 | sem_post(&pop_semaphore); |
| 49 | else |
| 50 | sem_post(&push_semaphore); |
| 51 | return ret; |
| 52 | } |
| 53 | |
| 54 | bool pop(Element*& item) |
| 55 | { |
| 56 | sem_wait(&pop_semaphore); |
| 57 | bool ret = circularQueue.pop(item); |
| 58 | if (ret) |
| 59 | sem_post(&push_semaphore); |
| 60 | else |
| 61 | sem_post(&pop_semaphore); |
| 62 | return ret; |
| 63 | } |
| 64 | |
| 65 | private: |
| 66 | CircularFifo<Element, size> circularQueue; |
| 67 | sem_t pop_semaphore; |
| 68 | sem_t push_semaphore; |
| 69 | }; |
| 70 | } |
| 71 | } |
| 72 | #endif /* INCLUDE_CMN_BLOCKINGCIRCULARFIFO_H_ */ |