使用sem_t + pthread_create的奇怪问题

Strange issue using sem_t + pthread_create

本文关键字:create 问题 pthread sem 使用      更新时间:2023-10-16

将参数sem_t传递给构造函数 A 时出现奇怪的行为。 预期输出5555,但我得到了5055。如果也有设计问题,请指出。

  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 }
int& k;
A(int k) : k(k){}

您正在将成员k初始化为对构造函数中本地k的引用。构造函数完成后,它将成为悬空引用,使用它是一种未定义的行为。