首页 文章

在Boost :: thread中究竟是什么join()? (C )

提问于
浏览
9

在Java中,我会做类似的事情:

Thread t = new MyThread();
t.start();

我通过调用start()方法启动线程 . 所以后来我可以这样做:

for (int i = 0; i < limit; ++i)
{
    Thread t = new MyThread();
    t.start();
}

创建一组线程并在run()方法中执行代码 .

但是,在C中,没有start()方法 . 使用Boost,如果我想要一个线程开始运行,我必须调用join()方法才能使线程运行 .

#include <iostream>
#include <boost/thread.hpp>

class Worker
{
public:
    Worker() 
    {
        // the thread is not-a-thread until we call start()
    }

    void start(int N)
    {
        m_Thread = boost::thread(&Worker::processQueue, this, N);
    }

    void join()
    {
        m_Thread.join();
    }

    void processQueue(unsigned N)
    {
        float ms = N * 1e3;
        boost::posix_time::milliseconds workTime(ms);

        std::cout << "Worker: started, will work for "
                  << ms << "ms"
                  << std::endl;

        // We're busy, honest!
        boost::this_thread::sleep(workTime);
        std::cout << "Worker: completed" << std::endl;
    }

private:

    boost::thread m_Thread;
};

int main(int argc, char* argv[])
{
    std::cout << "main: startup" << std::endl;

    Worker worker, w2, w3, w5;

    worker.start(3);
    w2.start(3);
    w3.start(3);
    w5.start(3);

    worker.join();
    w2.join();
    w3.join();
    w5.join();
    for (int i = 0; i < 100; ++i)
    {
        Worker w;
        w.start(3);
        w.join();
    }
    //std::cout << "main: waiting for thread" << std::endl;    

    std::cout << "main: done" << std::endl;

    return 0;
}

在上面的代码中,for循环创建了100个线程,通常我必须使用boost :: thread_group来添加线程函数,最后使用join_all()运行all . 但是,我不知道如何使用线程函数放入使用各种类成员的类 .

另一方面,上面的循环不会像Java中的循环那样 . 它将使每个线程按顺序执行,而不是像调用其自己的join()的其他分离线程一样执行 .

什么是Boost中的join()?另外请帮我创建一组共享同一个类的线程 .

2 回答

  • 13

    join 没有't start the thread, it blocks you until the thread you'重新加入完成 . 当您需要等待开始完成其运行的线程时使用它(例如 - 如果它计算某些东西而您需要结果) .

    启动该线程的是 boost::thread ,它创建线程并调用传递给它的线程函数(在您的情况下 - Worker::processQueue ) .

    你遇到循环问题的原因不是因为线程没有在完成之前等待它们执行 . 我猜你在Java中没有看到这个问题,因为调度的差异,即“未定义的行为” . after edit 在Java中,线程的行为略有不同,请参阅下面的注释以获取详细信息 . 这就解释了为什么你没有在Java中看到它 .

    Here's a question about the boost::thread_group . 阅读问题和答案中的代码,它会对您有所帮助 .

  • 5

    加入一个线程在Boost中做的和在Java中一样:它等待线程完成运行 .

    另外,如果我没记错的话,Boost的线程会在构建时运行 . 你没有明确地启动它们 .

相关问题