ha7ilm-csdr/tsmpool.h

44 wiersze
1.3 KiB
C

2016-06-04 20:54:17 +00: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 09:34:42 +00:00
#include <vector>
#include <pthread.h>
2017-01-10 09:34:42 +00:00
#define TSM_DEBUG 0
2017-01-19 16:08:49 +00:00
#include <stdio.h>
2017-01-12 16:45:59 +00:00
2017-01-10 09:34:42 +00:00
using namespace std;
2016-06-04 20:54:17 +00:00
typedef struct tsmthread_s
{
2016-06-04 15:42:29 +00:00
int read_index; //it always points to the next buffer to be read
2016-06-04 20:54:17 +00:00
} tsmthread_t;
2016-06-04 15:42:29 +00:00
class tsmpool
{
private:
vector<tsmthread_t*> threads;
vector<void*> buffers;
int threads_cntr;
pthread_mutex_t mutex;
int ok; //tsmpool is expected to be included in C-style programs.
// If something fails in the constructor, it will be seen here instead of a try{}catch{}
2016-06-04 15:42:29 +00:00
int write_index; //it always points to the next buffer to be written
int lowest_read_index; //unused
int my_read_index; //it is used when tsmpool is used as a single writer - single reader circular buffer
2016-06-04 15:42:29 +00:00
public:
const size_t size;
const int num;
int is_ok();
2016-06-04 15:42:29 +00:00
tsmpool(size_t size, int num);
void* get_write_buffer();
2016-09-20 21:52:58 +00:00
tsmthread_t* register_thread();
2019-01-24 14:37:14 +00:00
void remove_thread(tsmthread_t* thread);
2016-09-20 21:52:58 +00:00
void* get_read_buffer(tsmthread_t* thread);
int index_next(int index) { return (index+1==num)?0:index+1; }
int index_before(int index) { return (index-1<0)?num-1:index-1; }
2017-01-10 09:34:42 +00:00
};