C++线程程序不会终止
C++ thread program doesn't terminate
我不知道为什么我的代码没有终止。这可能是我在这里错过的一些明显的事情,请帮忙!
using namespace std;
int main(int argc, char* argv[])
{
MyClass *m = new MyClass();
thread t1(th,m);
delete m;
m=NULL;
t1.join();
return 0;
}
void th(MyClass *&p)
{
while(p!=NULL)
{
cout << "tick" << endl;
this_thread::sleep_for(chrono::seconds(1));
}
return;
}
线程被赋予了m
的副本,而不是对它的引用。使用引用包装器为其提供引用:
thread t1(th,std::ref(m));
程序可能会按预期结束;但是由于在一个线程上修改m
并在另一个线程上读取它而不同步的数据竞争,您仍然有未定义的行为。要解决此问题,请使用 std::atomic<MyClass*>
,或使用互斥锁保护两个访问。
相关文章:
- 堆栈粉碎终止程序
- 为什么我的显示功能会终止程序?
- 调用 raise(signal) 会终止 c++ 程序
- 使用终止程序的指针在数组中输入字符串
- C++ Argv[1] 终止程序,返回值 9009
- protobuf "oneof" sub-protobuf 对象指针终止程序
- 有没有办法避免在发生堆栈粉碎时终止程序
- c++ 终止程序的内存泄漏何时重要?
- C :CTRL D终止程序(Ubuntu)
- 用信号25终止程序,超过文件尺寸限制;为什么
- 是否有一种方法可以在输入负数时平均不包括负数,这是您终止程序的方式
- 正确关闭应用程序:终止程序的替代方案
- 提升线程终止程序
- Shell脚本终止程序,但导致无法写入输出文件
- 访问引用变量会终止程序
- 需要使用"enter"密钥终止程序
- C++按Enter键终止程序
- std::向量使用const_iterator终止程序
- Unicode导致关闭消息框终止程序
- 当我在函数中调用一个函数时,它会跳过代码并终止程序