一些提升线程问题C ++

时间:2011-07-29 04:04:47

标签: c++ multithreading boost

我正在使用boost :: thread,我遇到了一些问题。

问题是,有没有什么方法可以在最后一次加入之前加入一个帖子? 例如,

int id=1;
void temp()
{
    int theardID = id++;
    for(int i=0;i<3;i++)
    {
        cout<<theardID << " : "<<i<<endl;
        boost::this_thread::sleep(boost::posix_time::millisec(100));
    }
}
int main(void)
{
    boost::thread thrd1(temp);

    thrd1.join();

    boost::thread thrd2(temp);
    boost::thread thrd3(temp);    
    thrd2.join();
    thrd3.join();   
    return 0;
}

在这个简单的例子中,输出的顺序可能是:

1:0
1:1
1:2
2:0
3:0
3:1
2:1
2:2
3:2

如上例所示,我们可以看到thrd2和thrd3在thrd1完成后开始运行。

有没有办法让thrd2和thrd3在thrd1完成之前运行?

2 个答案:

答案 0 :(得分:3)

您可以使用Boost.Thread的condition variables进行同步,条件比join提供的条件更复杂。以下是基于您的示例:

#include <iostream>
#include <boost/thread.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>

boost::mutex mutex;
boost::condition_variable cond;

// These three variables protected by mutex
bool finishedFlag = false;
int finishedID = 0;
int finishedCount = 0;

int id=1;
void temp()
{
    int threadID = id++;
    for(int i=0;i<3;i++)
    {
        std::cout << threadID << " : " << i << std::endl;
        boost::this_thread::sleep(boost::posix_time::millisec(100));
    }

    {
        boost::lock_guard<boost::mutex> lock(mutex);
        finishedFlag = true;
        finishedID = threadID;
        ++finishedCount;
    }
    cond.notify_one();
}

int main(void)
{
    boost::thread thrd1(temp);
    boost::this_thread::sleep(boost::posix_time::millisec(300));
    boost::thread thrd2(temp);
    boost::thread thrd3(temp);

    boost::unique_lock<boost::mutex> lock(mutex);
    while (finishedCount < 3)
    {
        while (finishedFlag != true)
        {
            // mutex is released while we wait for cond to be signalled.
            cond.wait(lock);

            // mutex is reacquired as soon as we finish waiting.
        }
        finishedFlag = false;

        if (finishedID == 1)
        {
            // Do something special about thrd1 finishing
            std::cout << "thrd1 finished" << std::endl;
        }
    };

    // All 3 threads finished at this point.

    return 0;
}

答案 1 :(得分:3)

join函数表示“在该线程完成之前停止此线程”。它是一个简单的工具,用于一个简单的目的:确保在代码中超过这一点,完成线程X.

您想要做的不是join操作。你想要的是某种同步原语来交流和同步线程之间的行为。 Boost.Thread有一个number of alternatives for synchronization,从条件到互斥。