使用线程池库
Using thread pool library
本文关键字:线程 更新时间:2023-10-16
我试图使用Tyler Hardin的线程池类。该库可以在这里找到:https://github.com/Tyler-Hardin/thread_pool
我的代码是:#include "thread_pool.hpp"
#include <windows.h>
#include <iostream>
#include <list>
#include <string>
#include <sstream>
using namespace std;
const int num_threads = 8;
int getRandom(int min, int max)
{
return min + rand() % (max - min);
}
std::string to_string(int val)
{
std::ostringstream ss;
ss << val;
std::string str = ss.str();
return str;
}
string getResult(string param)
{
int time = getRandom(0, 500);
Sleep(time);
return ("Time spend here: " + to_string(time));
}
int main()
{
srand(time(NULL));
thread_pool pool(num_threads);
list<future<string>> results;
for(int i=100; i<=100000; i++)
{
std::future<string> buff = pool.async( function<string(string)>(getResult), "MyString" );
results.push_back( buff );
}
for(auto i=results.begin(); i != results.end(); i++)
{
i->get();
cout << endl;
}
return 0;
}
但似乎有什么问题,因为我面临着以下错误:
error: no matching function for call to 'thread_pool::async(std::function<std::basic_string<char>(std::basic_string<char>)>, const char [9])
error: use of deleted function 'std::future<_Res>::future(const std::future<_Res>&) [with _Res = std::basic_string<char>]'|
我在这个电话中做错了什么:
std::future<string> buff = pool.async( function<string(string)>(getResult), "MyString" );
程序应该在每个线程完成它们的任务后立即打印每个线程的睡眠时间
错误1:函数匹配
很确定你正在使用的Windows编译器不知道在匹配async
时将const char [9]
类型的字符串文字匹配到std::string
。这是两层隐式转换,这是不允许的:
const char [9]
--> const char*
--> std::basic_string<char>(const char* s, const Allocator& alloc = Allocator() );
我不确定编译器是否应该将其视为单个或两个单独的隐式转换。
无论如何,您可以通过显式地将参数转换为std::string
std::future<string> buff = pool.async( function<string(string)>(getResult), std::string("MyString") );
错误2:使用deleted…
使用move构造函数。复制构造函数被标记为deleted
results.push_back( std::move(buff) );
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 在C++中使用cURL和多线程
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 在cuda线程之间共享大量常量数据
- 如何将元素添加到数组的线程安全函数?
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 异常属于C++中的线程还是进程
- C++中的线程安全删除
- C++使用params创建线程函数会导致转换错误
- 类与私有变量的其他类之间的线程安全性
- CoInitialize()在单独的线程上崩溃而不返回
- c++中的线程池
- 线程之间的布尔停止信号
- 为什么std::async使用同一个线程运行函数
- 用于矢量处理的多个线程
- C++为线程工作动态地分割例程
- 为什么我不能在 while 循环中创建线程?