C++0x has no semaphores? How to synchronize threads?

后端 未结 10 976
无人及你
无人及你 2020-11-22 07:18

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

10条回答
  •  执笔经年
    2020-11-22 07:45

    Also can be useful RAII semaphore wrapper in threads:

    class ScopedSemaphore
    {
    public:
        explicit ScopedSemaphore(Semaphore& sem) : m_Semaphore(sem) { m_Semaphore.Wait(); }
        ScopedSemaphore(const ScopedSemaphore&) = delete;
        ~ScopedSemaphore() { m_Semaphore.Notify(); }
    
       ScopedSemaphore& operator=(const ScopedSemaphore&) = delete;
    
    private:
        Semaphore& m_Semaphore;
    };
    

    Usage example in multithread app:

    boost::ptr_vector threads;
    Semaphore semaphore;
    
    for (...)
    {
        ...
        auto t = new std::thread([..., &semaphore]
        {
            ScopedSemaphore scopedSemaphore(semaphore);
            ...
        }
        );
        threads.push_back(t);
    }
    
    for (auto& t : threads)
        t.join();
    

提交回复
热议问题