简体   繁体   English

使用sem_t + pthread_create的奇怪问题

[英]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 . 将参数sem_t传递给构造函数A时发生奇怪的行为。预期输出为5555但我得到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 }
int& k;
A(int k) : k(k){}

You are initializing member k as reference to local k in constructor. 您正在初始化成员k以引用构造函数中的本地k After constructor finishes it becomes dangling reference and using it is undefined behavior. 构造函数完成后,它将成为悬空引用,并且使用它是未定义的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM