簡體   English   中英

使用sem_t + pthread_create的奇怪問題

[英]Strange issue using sem_t + pthread_create

將參數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 構造函數完成后,它將成為懸空引用,並且使用它是未定義的行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM