使用线程池库

Using thread pool library

我正在尝试使用 Tyler Hardin 的线程池 class。 图书馆可以在这里找到: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 匹配。这是 two levels of implicit conversion, which is not allowed :

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:使用已删除的 ...

使用移动构造函数。复制构造函数被标记为已删除

results.push_back( std::move(buff) );