使用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
的引用。构造函数完成后,它将成为悬空引用,使用它是一种未定义的行为。
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题