semaphores

 avatar
tuhuuduc
c_cpp
a year ago
669 B
6
Indexable
#include <iostream> 
#include <semaphore> 
#include <thread> 
using namespace std; 

counting_semaphore<10> semaphore(3); // for couting semaphore
//binary_semaphore semaphore(1); // for binary semaphore
void worker(int id) 
{ 
    // aquiring 
    semaphore.acquire(); 

    // doing some work 
    cout << "Thread " << id << " acquired the semaphore." << endl; 

    // releasing 
    semaphore.release(); 
    cout << "Thread " << id << " released the semaphore." << endl; 
}

int main() 
{ 
    thread t1(worker, 1); 
    thread t2(worker, 2); 
    thread t3(worker, 3); 
    t1.join(); 
    t2.join(); 
    t3.join(); 
    return 0; 
}
Editor is loading...
Leave a Comment