Jason Sams | d19f10d | 2009-05-22 14:03:28 -0700 | [diff] [blame^] | 1 | /* |
| 2 | * Copyright (C) 2009 The Android Open Source Project |
| 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 ANDROID_RS_LOCKLESS_FIFO_H |
| 18 | #define ANDROID_RS_LOCKLESS_FIFO_H |
| 19 | |
| 20 | |
| 21 | #include <stdint.h> |
| 22 | #include <sys/types.h> |
| 23 | #include <stdlib.h> |
| 24 | #include <pthread.h> |
| 25 | |
| 26 | namespace android { |
| 27 | |
| 28 | |
| 29 | // A simple FIFO to be used as a producer / consumer between two |
| 30 | // threads. One is writer and one is reader. The common cases |
| 31 | // will not require locking. It is not threadsafe for multiple |
| 32 | // readers or writers by design. |
| 33 | |
| 34 | class LocklessCommandFifo |
| 35 | { |
| 36 | public: |
| 37 | bool init(uint32_t size); |
| 38 | |
| 39 | LocklessCommandFifo(); |
| 40 | ~LocklessCommandFifo(); |
| 41 | |
| 42 | |
| 43 | protected: |
| 44 | uint8_t * volatile mPut; |
| 45 | uint8_t * volatile mGet; |
| 46 | uint8_t * mBuffer; |
| 47 | uint8_t * mEnd; |
| 48 | uint8_t mSize; |
| 49 | |
| 50 | pthread_mutex_t mMutex; |
| 51 | pthread_cond_t mCondition; |
| 52 | |
| 53 | public: |
| 54 | void * reserve(uint32_t bytes); |
| 55 | void commit(uint32_t command, uint32_t bytes); |
| 56 | void commitSync(uint32_t command, uint32_t bytes); |
| 57 | |
| 58 | void flush(); |
| 59 | const void * get(uint32_t *command, uint32_t *bytesData); |
| 60 | void next(); |
| 61 | |
| 62 | void makeSpace(uint32_t bytes); |
| 63 | |
| 64 | bool isEmpty() const; |
| 65 | uint32_t getFreeSpace() const; |
| 66 | |
| 67 | |
| 68 | private: |
| 69 | void dumpState(const char *) const; |
| 70 | }; |
| 71 | |
| 72 | |
| 73 | } |
| 74 | #endif |