fork(1) download
  1. #include <iostream>
  2. #include <semaphore.h>
  3. using namespace std;
  4.  
  5. int main() {
  6. sem_t my_sem;
  7. int val,ec;
  8. ec=sem_init(&my_sem, 0, 1);
  9. if (ec)
  10. cout<<"Error "<<ec<<endl;
  11. else {
  12. sem_getvalue(&my_sem, &val);
  13. cout<<val<<endl;
  14. sem_post(&my_sem);
  15. sem_getvalue(&my_sem, &val);
  16. cout<<val<<" !!!"<<endl;
  17. sem_wait(&my_sem);
  18. sem_getvalue(&my_sem, &val);
  19. cout<<val<<endl;
  20. sem_wait(&my_sem);
  21. sem_getvalue(&my_sem, &val);
  22. cout<<val<<endl;
  23. sem_trywait(&my_sem); // ok, here we are in a single thread, so it's same thread
  24. if (ec) {
  25. sem_getvalue(&my_sem, &val);
  26. cout<<val<<endl;
  27. }
  28. else cout << "Couldn't acquire"<<endl;
  29. }
  30. return 0;
  31. }
Success #stdin #stdout 0s 4276KB
stdin
Standard input is empty
stdout
1
2   !!!
1
0
Couldn't acquire