【发布时间】:2011-09-08 15:54:32
【问题描述】:
在 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()运行所有。但是,我不知道如何将线程函数放入一个使用各种类成员的类中。
另一方面,上述循环的行为与 Java 中的循环不同。它将使每个线程按顺序执行,而不是像其他单独的线程一样一次全部执行,它们自己的 join() 被调用。
Boost 中的 join() 到底是什么?另外请帮我创建一组共享同一类的线程。
【问题讨论】:
标签: c++ multithreading boost