2016-06-05 04:54:17 +08:00
|
|
|
//tsmpool stands for Thread-Safe Memory Pool.
|
|
|
|
|
|
|
|
//It implements a big circular buffer that one thread writes into, and multiple threads read from.
|
|
|
|
//The reader threads have lower priority than the writer thread (they can be left behind if the don't read fast enough).
|
|
|
|
|
2017-01-10 17:34:42 +08:00
|
|
|
#include <vector>
|
|
|
|
|
|
|
|
using namespace std;
|
|
|
|
|
2016-06-05 04:54:17 +08:00
|
|
|
typedef struct tsmthread_s
|
|
|
|
{
|
2016-06-04 23:42:29 +08:00
|
|
|
int read_index; //it always points to the next buffer to be read
|
2016-06-05 04:54:17 +08:00
|
|
|
} tsmthread_t;
|
2016-06-04 23:42:29 +08:00
|
|
|
|
|
|
|
class tsmpool
|
|
|
|
{
|
|
|
|
private:
|
|
|
|
size_t size;
|
|
|
|
int num;
|
|
|
|
vector<tsmthread_t*> threads;
|
|
|
|
vector<void*> buffers;
|
|
|
|
int threads_cntr;
|
|
|
|
pthread_mutex_t mutex;
|
|
|
|
int ok;
|
|
|
|
int write_index; //it always points to the next buffer to be written
|
2016-06-05 05:05:38 +08:00
|
|
|
int lowest_read_index; //unused
|
2016-06-08 04:14:36 +08:00
|
|
|
int my_read_index; //it is used when tsmpool is used as a single writer - single reader circular buffer
|
2016-06-04 23:42:29 +08:00
|
|
|
|
|
|
|
public:
|
|
|
|
size_t get_size();
|
|
|
|
tsmpool(size_t size, int num);
|
|
|
|
void* get_write_buffer();
|
2016-09-21 05:52:58 +08:00
|
|
|
tsmthread_t* register_thread();
|
|
|
|
int remove_thread(tsmthread_t* thread);
|
|
|
|
void* get_read_buffer(tsmthread_t* thread);
|
2016-06-04 23:42:29 +08:00
|
|
|
int index_next(int index) { return (index+1==size)?0:index; }
|
|
|
|
int index_before(int index) { return (index-1<0)?size-1:index; }
|
2017-01-10 17:34:42 +08:00
|
|
|
};
|