本文介绍了C ++ 0x没有信号量?如何同步线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是不是C ++ 0x会没有信号量?在Stack Overflow上已经有一些关于信号量使用的问题。我使用它们(posix信号量)让一个线程等待另一个线程中的一些事件:

Is it true that C++0x will come without semaphores? There are already some questions on Stack Overflow regarding the use of semaphores. I use them (posix semaphores) all the time to let a thread wait for some event in another thread:

void thread0(...)
{
  doSomething0();

  event1.wait();

  ...
}

void thread1(...)
{
  doSomething1();

  event1.post();

  ...
}

用互斥体:

void thread0(...)
{
  doSomething0();

  event1.lock(); event1.unlock();

  ...
}

void thread1(...)
{
  event1.lock();

  doSomethingth1();

  event1.unlock();

  ...
}

问题:它不能保证thread1首先锁定互斥体(假定同一个线程应该锁定和解锁互斥体,你也不能在thread0和thread1开始之前锁定event1)。

Problem: It's ugly and it's not guaranteed that thread1 locks the mutex first (Given that the same thread should lock and unlock a mutex, you also can't lock event1 before thread0 and thread1 started).

因此,既然boost也没有信号量,那么最简单的方法是什么呢?

So since boost doesn't have semaphores either, what is the simplest way to achieve the above?

推荐答案

一个来自互斥体和条件变量:

You can easily build one from a mutex and a condition variable:

#include <boost/thread/condition.hpp>
#include <boost/thread/mutex.hpp>

class semaphore
{
private:
    boost::mutex mutex_;
    boost::condition_variable condition_;
    unsigned long count_;

public:
    semaphore()
        : count_()
    {}

    void notify()
    {
        boost::mutex::scoped_lock lock(mutex_);
        ++count_;
        condition_.notify_one();
    }

    void wait()
    {
        boost::mutex::scoped_lock lock(mutex_);
        while(!count_)
            condition_.wait(lock);
        --count_;
    }
};

这篇关于C ++ 0x没有信号量?如何同步线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 12:08
查看更多