我正在尝试使用boost :: asio创建一个有限的线程池类.但是我被困在某一点可以帮助我.
唯一的问题是我应该减少反击的地方?
代码无法按预期工作.
问题是我不知道我的线程何时完成执行以及我将如何知道它已经返回池中
#include <boost/asio.hpp>
#include <iostream>
#include <boost/thread/thread.hpp>
#include <boost/bind.hpp>
#include <boost/thread/mutex.hpp>
#include <stack>
using namespace std;
using namespace boost;
class ThreadPool
{
static int count;
int NoOfThread;
thread_group grp;
mutex mutex_;
asio::io_service io_service;
int counter;
stack<thread*> thStk ;
public:
ThreadPool(int num)
{
NoOfThread = num;
counter = 0;
mutex::scoped_lock lock(mutex_);
if(count == 0)
count++;
else
return;
for(int i=0 ; i<num ; ++i)
{
thStk.push(grp.create_thread(boost::bind(&asio::io_service::run, &io_service)));
}
}
~ThreadPool()
{
io_service.stop();
grp.join_all();
}
thread* getThread()
{ …Run Code Online (Sandbox Code Playgroud) 是否可以使用boost的线程创建线程池?我正在寻找所有的升级库,我找不到线程池管理器(或类似的东西)......有没有办法做到这一点?
TNX!
我正在努力消除我的一些困惑.我偶然发现了boost :: asio :: thread_pool,我认为可以使用以某种方式自动组合,boost::asio::io_context并且boost::thread::thread_group经常建议(这里或这里).似乎这个asio特定的池可以用于post任务,但另一方面,某些网络类型resolver需要传递一个对象io_context作为构造函数参数,而这些参数thread_pool不是也不是从中派生出来的.
main()我的 C++ 方法中有这行代码:
std::thread foo (bar);
Run Code Online (Sandbox Code Playgroud)
这很好用。但是,我想根据外部输入随时运行相同的线程。如何重新使用此线程再次运行该线程?
我这样做的原因是我有两个需要同时运行的函数:一个是阻塞函数并接受输入 x,并以设定的时间间隔将数据输出到输出。另一个是阻塞并根据外部输入产生输出 y。这基本上应该是这样的:
int shared_x = 0;
int producer_x = 0;
int consumer_x = 0;
std::thread producer (foo); //Modifies foo_x
std::thread consumer (bar); //Outputs based on foo2_x
while( ;; ) {
if(producer .join()) {
shared_x = producer_x;
//How should I restart the thread here?
}
if(consumer.join()) {
consumer_x = shared_x;
//Here too?
}
}
Run Code Online (Sandbox Code Playgroud)
这似乎处理了整个线程安全问题,并允许它们同时安全地运行而无需等待。唯一的问题是我不知道如何重新启动线程。我该怎么做呢?
我使用Visual Studio 2012,并尝试使静态库UDT正常工作。不幸的是,我无法编译将UDT库链接到其自身的项目,我在Windows SDK标头中遇到有关类型或宏重新定义的159个奇怪的错误。
c:\program files\windows kits\8.0\include\shared\ws2def.h(96): warning C4005: 'AF_IPX' : macro redefinition
2> c:\program files\windows kits\8.0\include\um\winsock.h(452) : see previous definition of 'AF_IPX'
2>c:\program files\windows kits\8.0\include\shared\ws2def.h(136): warning C4005: 'AF_MAX' : macro redefinition
2> c:\program files\windows kits\8.0\include\um\winsock.h(471) : see previous definition of 'AF_MAX'
2>c:\program files\windows kits\8.0\include\shared\ws2def.h(173): warning C4005: 'SO_DONTLINGER' : macro redefinition
2> c:\program files\windows kits\8.0\include\um\winsock.h(394) : see previous definition of 'SO_DONTLINGER'
2>c:\program files\windows kits\8.0\include\shared\ws2def.h(217): error C2011: 'sockaddr' : 'struct' type redefinition
2> c:\program files\windows kits\8.0\include\um\winsock.h(477) : see declaration …
c++ ×7
boost-asio ×3
boost ×2
threadpool ×2
boost-thread ×1
function ×1
pool ×1
sockets ×1
std ×1
windows ×1