C++线程程序不会终止

C++ thread program doesn't terminate

本文关键字:终止 程序 线程 C++      更新时间:2023-10-16

我不知道为什么我的代码没有终止。这可能是我在这里错过的一些明显的事情,请帮忙!

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*> ,或使用互斥锁保护两个访问。