I am trying to build a library that would write to a single file, and would be able to work in a multi-threaded environment. The requirements are:
- No concurrency problems will occur while writing to the file.
- The order in which threads are handled is not important.
- The library should be non blocking, i.e. the write and flush functions will return before the given buffer had been written.
Here’s what I have so far:
int write2device(char *buffer, int length) {
Task * task = new Task(id++,buffer,length);
pthread_t * thread = new pthread_t;
Argument * arg = new Argument; //A sturct with pthread_t and task fields
arg->task = task;
arg->thread = thread;
pthread_create(thread,NULL,deamonWrite,arg);
return 0;
}
void wait(Argument * arg) {
//manager is a singleton class that handles the threads database and related
//issues
manager->pushDeamon(arg->thread);
manager->lock(arg->task->getId()); //mutex - only one thread can write
}
void * deamonWrite(void * arg) {
Argument * temp = (Argument *) arg;
wait(temp);
//critical section
//will add signal() later
return NULL;
}
The idea is that for every thread calling write2device I open a thread that runs deamonWrite(). This function has the structure of wait() -> critical section -> signal().
In wait, if someone else is writing I will (haven’t done yet) suspend the thread so that the user won’t wait till it’s done writing.
I have two questions:
- How do I implement the mutex (lock function)? I understand that This must be an atomic function, sense several threads trying to acquire a lock might result in chaos.
- Is my general structure in the right way?
I am new to concurrency and would appreciate any thoughts on this matter – thanks!
Push the
Taskstructures to a queue/vector and process them sequentially from a single thread instead of multiple threads for each task individually. The only place where you’ll need a mutex is when pushing to and pulling from the queue. As Ben correctly noted in the comments, you should leave the implementation of thread synchronization primitives (mutex, critical section) to the OS and/or whatever system API you’re allowed to use.