C ++线程不能像我期望的那样工作?

时间:2016-08-17 15:49:01

标签: c++ multithreading

我正在制作更大的程序,我想要使用线程,所以首先我试图找出线程实际如何工作所以我创建了一个简单的程序,我无法理解为什么我没有收到消息var arr = [{Analytics:16}, {Technology:12}, {Medical:20}, {Operations:40}]; _.map(arr,function(m){return _.values(m)[0]}); 早于"Bomberman has just put a bomb. Wait for the boom."

任何人都可以告诉我为什么它不像我期望的那样工作?

"The bomb has just detonated."

2 个答案:

答案 0 :(得分:4)

您的问题是您在创建线程后立即加入该线程,这意味着您只是在技术意义上使用多线程:您确实创建了另一个线程,并且&#&# 39; s(可能)将在另一个CPU核心上运行,但主机线程只是闲置而另一个线程工作。

您需要在本地存储thread对象,以便稍后加入。

class CBomb
{
public:
    CBomb ( void )
    : m_Owner ( nullptr ),
    bomb_thread(&CBomb::Timer, this)
    {
    }
    std::thread bomb_thread; //This needs to be a member of this object. Whether you make it public or not is a matter of your design approach.
private:
    void Timer ( void )
    {
        this_thread::sleep_for( chrono::seconds( 3 ) );
        cout << "The bomb has just detonated." << endl;
    }

    CBomberman * m_Owner;
};

class CBomberman
{
public:
    CBomberman ( void )
    : m_Bomb ( nullptr )
    {

    }

    bool PutBomb ( void )
    {
        if( m_Bomb == nullptr )
        {
            m_Bomb = new CBomb();//Don't delete the object immediately after creating it. What were you expecting to have happen if you did?
            return true;
        }
        else
        {
            cout << "The bomb has already been put." << endl;
            return false;
        }
    }
    CBomb * m_Bomb;
};

int main()
{
    CBomberman bomberman;

    bomberman.PutBomb();
    cout << "Bomberman has just put a bomb. Wait for the boom." << endl;
    bomberman.m_bomb->bomb_thread.join(); //If we hit the end before the thread concludes, there could be some errors.

    return 0;
}

答案 1 :(得分:0)

因为您在创建join后立即致电other_thread other_threadjoin调用阻塞主线程并等待other_thread退出。请参阅http://en.cppreference.com/w/cpp/thread/thread/join上std :: thread :: join上的文档。