使用线程池库

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) );