curiosul curiosul - 1 year ago 142
C++ Question

Using thread pool library

I'm trying to use Tyler Hardin's thread pool class.
The library can be found here:

My code is:

#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);
return ("Time spend here: " + to_string(time));

int main()

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++)
cout << endl;
return 0;

But something seems to be wrong as I am facing with the following errors:

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>]'|

What am I doing wrong in this call:

std::future<string> buff = pool.async( function<string(string)>(getResult), "MyString" );

The program should print the sleep time withing every thread right after every thread finish their job.

Answer Source

Error 1 : function matching

Pretty sure the Windows compiler you are using doesn't know to match the string literal of type const char [9] to a std::string when matching async. This is 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() );

I am not sure whether the compiler should consider it to be a single or two separate implicit conversion.
Anyway, you could fix it by explicitly converting the parameter to a std::string

std::future<string> buff = pool.async( function<string(string)>(getResult), std::string("MyString") );

Error 2 : use of deleted ...

Use the move constructor. The copy constructor is marked as deleted

results.push_back( std::move(buff) );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download