多线程C++消息传递

gro*_*uma 6 c++ multithreading boost boost-thread

我的任务是修改同步C程序,以便它可以并行运行.我们的目标是让它尽可能便携,因为它是许多人使用的开源程序.因此,我认为最好将程序包装在C++层中,这样我就可以利用便携式的boost库.我已经完成了这一切,一切似乎按预期工作.

我遇到的问题是决定在线程之间传递消息的最佳方法是什么.幸运的是,该程序的体系结构是多生产者和单个消费者的体系结构.更好的是,消息的顺序并不重要.我已经读过单一生产者/单一消费者(SPSC)队列将受益于这种架构.那些有多线程编程经验的人有什么建议吗?我对这些东西很新.此外,任何使用boost实现SPSC的代码示例都将非常感激.

byt*_*ter 7

以下是我用于合作多任务/多线程库(MACE)的技术http://bytemaster.github.com/mace/.除了队列为空时,它具有无锁的优点.

struct task {
   boost::function<void()> func;
   task* next;
};


boost::mutex                     task_ready_mutex;
boost::condition_variable        task_ready;
boost::atomic<task*>             task_in_queue;

// this can be called from any thread
void thread::post_task( task* t ) {
     // atomically post the task to the queue.
     task* stale_head = task_in_queue.load(boost::memory_order_relaxed);
     do { t->next = stale_head;
     } while( !task_in_queue.compare_exchange_weak( stale_head, t, boost::memory_order_release ) );

   // Because only one thread can post the 'first task', only that thread will attempt
   // to aquire the lock and therefore there should be no contention on this lock except
   // when *this thread is about to block on a wait condition.  
    if( !stale_head ) { 
        boost::unique_lock<boost::mutex> lock(task_ready_mutex);
        task_ready.notify_one();
    }
}

// this is the consumer thread.
void process_tasks() {
  while( !done ) {
   // this will atomically pop everything that has been posted so far.
   pending = task_in_queue.exchange(0,boost::memory_order_consume);
   // pending is a linked list in 'reverse post order', so process them
   // from tail to head if you want to maintain order.

   if( !pending ) { // lock scope
      boost::unique_lock<boost::mutex> lock(task_ready_mutex);                
      // check one last time while holding the lock before blocking.
      if( !task_in_queue ) task_ready.wait( lock );
   }
 }
Run Code Online (Sandbox Code Playgroud)