anthonywilliams / ccia_code_samples

Code samples for C++ Concurrency in Action
687 stars 214 forks source link

Listing 9.3 parallel_accumulate using a thread pool with waitable tasks do not compile #17

Open keitee opened 2 years ago

keitee commented 2 years ago

Hi, wonder if there is anyone who have manged to get it working.

Firstly, errors on submit() function like:

:9749:52: required from here :9678:18: error: no matching function for call to ‘cxx_thread_pool::listing_9_2::thread_pool::submit( cxx_thread_pool::accumulate_block<__gnu_cxx::__normal_iterator<int*, std::vector >, int>&)’

9678 | futures[i] = pool.submit(ac); :9618:55: note: candidate: ‘template std::future<typename std::result_of<F()>::type> cxx_thread_pool::listing_9_2::thread_pool::submit(F)’ 9618 | std::future<typename std::result_of<F()>::type> submit(F f) | ^~ :9618:55: note: template argument deduction/substitution failed: : In substitution of ‘template std::future<typename std::result_of<F()>::type> cxx_thread_pool::listing_9_2::thread_pool::submit(F) [with F = cxx_thread_pool::accumulate_block<gnu_cxx::normal_iterator<int*, std::vector >, int>]’: :9678:18: required from ‘T cxx_thread_pool::parallel_accumulate(Iterator, Iterator, T) [with Iterator = gnu_cxx::normal_iterator<int, std::vector >; T = int]’ :9749:52: required from here :9618:55: error: no type named ‘type’ in ‘class std::result_of<cxx_thread_pool::accumulate_block<__gnu_cxx::__normal_iterator<int, std::vector >, int>()>’

Secondly, not sure how the task submitted gets the range of block to work on since submit() expects F that has no arguments.

Any help or suggestions?

Many thanks

HlodricIB commented 2 years ago

I didn't try to compile this Listing yet, but, as I can see, in Listing9.3 (here), in that block(listed below) have to be next code (bolded): for(unsigned long i=0;i<(num_blocks-1);++i) { Iterator block_end=block_start; std::advance(block_end,block_size); futures[i]=pool.submit([=]{ accumulate_block<Iterator,T>()(block_start,block_end); }); block_start=block_end; }

That code is presented in the second edition of the book. So, you wrapping call of _accumulateblock in a lambda expression and there is no need to pass any arguments to submit function directly.

ITHelpDec commented 1 year ago

Hey, @keitee!

Maybe a bit of an old post, but I've just posted a PR here showing what steps I took to resolve the issue (it just needed a simple return within the lambda function).

I used the listing from the book like you did, but had to make a few more tweaks to the listing from this repo in order to get them singing from the same hymn sheet before I could apply the fix.

I've a ready-to-go example in on my own repo here if it's of any use.

Hope this helps.