我正在尝试构建一个可以写入单个文件的库,并且能够在多线程环境中工作。要求是:
- 写入文件时不会出现并发问题。
- 处理线程的顺序并不重要。
- 库应该是非阻塞的,即写入和刷新函数将在给定缓冲区被写入之前返回。
这是我到目前为止所拥有的:
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;
}
这个想法是,对于每个调用 write2device 的线程,我都会打开一个运行 deamonWrite() 的线程。这个函数的结构是wait() ->critical section -> signal()。在等待中,如果其他人正在写作,我将(尚未完成)暂停线程,以便用户不会等到它完成写作。
我有两个问题:
- 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!