Recherche…


Introduction

Les sémaphores ne sont pas disponibles en C ++ pour le moment, mais peuvent facilement être implémentés avec un mutex et une variable de condition.

Cet exemple provient de:

C ++ 0x n'a pas de sémaphores? Comment synchroniser les threads?

Sémaphore C ++ 11

#include <mutex>
#include <condition_variable>
        
class Semaphore {
public:
    Semaphore (int count_ = 0)
    : count(count_) 
    {
    }
    
    inline void notify( int tid ) {
        std::unique_lock<std::mutex> lock(mtx);
        count++;
        cout << "thread " << tid <<  " notify" << endl;
        //notify the waiting thread
        cv.notify_one();
    }
    inline void wait( int tid ) {
        std::unique_lock<std::mutex> lock(mtx);
        while(count == 0) {
            cout << "thread " << tid << " wait" << endl;
            //wait on the mutex until notify is called
            cv.wait(lock);
            cout << "thread " << tid << " run" << endl;
        }
        count--;
    }
private:
    std::mutex mtx;
    std::condition_variable cv;
    int count;
};

Classe de sémaphore en action

La fonction suivante ajoute quatre threads. Trois threads sont en compétition pour le sémaphore, dont le nombre est de un. Un thread plus lent appelle notify_one() , permettant à l'un des threads en attente de continuer.

Le résultat est que s1 commence immédiatement à tourner, faisant en sorte que le count utilisation du sémaphore reste inférieur à 1. Les autres threads attendent à tour de rôle la variable condition jusqu'à ce que notify () soit appelé.

int main()
{
    Semaphore sem(1);
    
    thread s1([&]() {
        while(true) {
            this_thread::sleep_for(std::chrono::seconds(5));
            sem.wait( 1 );
        }           
    });
    thread s2([&]() {
        while(true){
            sem.wait( 2 );
        }
    });
    thread s3([&]() {
        while(true) {
            this_thread::sleep_for(std::chrono::milliseconds(600));
            sem.wait( 3 );
        }
    });
    thread s4([&]() {
        while(true) {
            this_thread::sleep_for(std::chrono::seconds(5));
            sem.notify( 4 );
        }
    });
    
    
    s1.join();
    s2.join();
    s3.join();
    s4.join();

    ...
    }


Modified text is an extract of the original Stack Overflow Documentation
Sous licence CC BY-SA 3.0
Non affilié à Stack Overflow