【问题标题】:Thread join waits forever: join hangs or waits forever线程连接永远等待:连接挂起或永远等待
【发布时间】:2013-11-18 12:44:42
【问题描述】:

我有如下代码

void CLogThread::run()
{
    m_alive = True;  //only place where m_alive (declared volatile) set to true 

    while (m_alive)
    {
        //logic here
    }   
}


void CLogThread::stop()
{
    m_alive = False;
}




void CThreadManager::uninit() throw()
{
    try
    {
        if (m_pLogThread != NULL)
        {
            m_pLogThread->stop();
            (void)m_pLogThread->getThreadControl().join();
            m_pLogThread->uninit();
            m_pLogThread = NULL;    
        }

    }
    catch (...)
    {
    }
}

我正在尝试优雅地退出该过程。但问题是我很少看到该程序在加入时挂起。

线程在无限while循环中仍然处于活动状态。即使在调用 stop 之后 m_alive 值也是“true”(在 stop 中将其设置为 false)。 m_alive 被声明为 volatile。

【问题讨论】:

  • 我无法找出问题所在,有什么办法可以告诉加入等待一定时间后出来吗?
  • 使用实际的同步对象(受互斥锁保护的临界区、信号量等),而不是简单的 volatile 变量。

标签: multithreading pthreads pthread-join


【解决方案1】:

找到了m_alive为真的原因。

这是因为,当我们创建一个线程(通常调用“start”函数)时,调用的是不同的线程并继续执行。当“开始”完成并调用停止时,新线程尚未安排。所以“运行”没有开始。稍后运行开始时,再次将 m_alive 的值从 false 重置为 true....

【讨论】:

    猜你喜欢
    • 2011-10-12
    • 2012-09-19
    • 1970-01-01
    • 2013-11-24
    • 2012-02-24
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多