C++ boost::线程组在线程完成后永远挂起
我有一个简单的程序,计算n的lemoine(并最小化p),对于范围内的所有n。我正在尝试使用boost::thread_组来使用指定数量的内核来分发作业。这是我的密码:C++ boost::线程组在线程完成后永远挂起,c++,boost,C++,Boost,我有一个简单的程序,计算n的lemoine(并最小化p),对于范围内的所有n。我正在尝试使用boost::thread_组来使用指定数量的内核来分发作业。这是我的密码: int is_prime(unsigned int number) { if (number <= 1) return 0; unsigned int i; for (i=2; i*i<=number; i++) { if (number
int is_prime(unsigned int number)
{
if (number <= 1) return 0;
unsigned int i;
for (i=2; i*i<=number; i++) {
if (number % i == 0) return 0;
}
return 1;
}
void lemoine(unsigned int n)
{
unsigned int q, p;
for (q = n/2; q > 0; q--) {
p = n - 2 * q;
if (is_prime(p) && is_prime(q)) {
printf("%d = %d + 2*%d\n", n, p, q);
return;
}
}
}
void guess(unsigned int lower, unsigned int upper, unsigned int cores)
{
unsigned int n;
boost::asio::io_service svc;
boost::asio::io_service::work work(svc);
boost::thread_group threadpool;
for (int i = 0; i < cores; i++) {
threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &svc));
}
for (n = lower; n <= upper; n+=2) {
svc.post(std::bind(lemoine, n));
}
threadpool.join_all();
}
int是素数(无符号整数)
{
如果(number您的代码挂起调用io_服务::run
,因为您创建了io_服务::work
对象()。io_服务::run
只能在调用work
的析构函数时返回-在您的情况下,这是不可能的,因为在join_all
(当函数超出范围时)。您可以通过在堆上创建work
实例来解决此问题(然后您可以手动删除此对象,调用work
和io_service::run
的dtor可以返回):
void guess(无符号整数下限、无符号整数上限、无符号整数核)
{
无符号整数n;
boost::asio::io_服务svc;
std::unique_ptr work=//已添加
std::make_unique(svc);//已添加
boost::线程组线程池;
对于(int i=0;ivoid guess(unsigned int lower, unsigned int upper, unsigned int cores)
{
unsigned int n;
boost::asio::io_service svc;
std::unique_ptr<boost::asio::io_service::work> work = // ADDED
std::make_unique<boost::asio::io_service::work>(svc); // ADDED
boost::thread_group threadpool;
for (int i = 0; i < cores; i++) {
threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &svc));
}
for (n = lower; n <= upper; n+=2) {
svc.post(std::bind(lemoine, n));
}
work.reset(); // delete work, ADDED
threadpool.join_all();
}