0

我正在尝试构建一个可以写入单个文件的库,并且能够在多线程环境中工作。要求是:

  1. 写入文件时不会出现并发问题。
  2. 处理线程的顺序并不重要。
  3. 库应该是非阻塞的,即写入和刷新函数将在给定缓冲区被写入之前返回。

这是我到目前为止所拥有的:

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()。在等待中,如果其他人正在写作,我将(尚未完成)暂停线程,以便用户不会等到它完成写作。

我有两个问题:

  1. 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.
  2. Is my general structure in the right way?

I am new to concurrency and would appreciate any thoughts on this matter - thanks!

4

1 回答 1

4

Push the Task structures 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.

于 2012-05-05T22:05:27.307 回答