Q:

Strange issue using sem_t + pthread_create

Strange behaviour when passing argument sem_t to constructor A. Expected output was 5555 but i got 5055. Please point out if there are design problems too.
  1 #include <iostream>
  2 #include <pthread.h>
  3 #include <semaphore.h>
  4 using namespace std;
  5 
  6 class A {
  7   public:
  8     pthread_t thr_id;
  9     int& k;
 10 
 11     A(sem_t& sem, int k) : k(k){}
 12     A(int k) : k(k){}
 13 
 14     void start(){
 15       cout << k;
 16       pthread_create(&thr_id, NULL, foo2, NULL);
 17       cout << k;
 18     }
 19     void join(){
 20       pthread_join(thr_id, NULL);
 21     }
 22     static void* foo2(void* i){}
 23 };
 24 
 25 int main() {
 26   sem_t sem;
 27   A* ac1 = new A(sem, 5);
 28   ac1->start();
 29   ac1->join();
 30   A* ac2 = new A(5);
 31   ac2->start();
 32   ac2->join();
 33  return 0;
 34 }

A:

int& k;
A(int k) : k(k){}

You are initializing member k as reference to local k in constructor. After constructor finishes it becomes dangling reference and using it is undefined behavior.

