mercredi 23 janvier 2019

How to pass struct elements to asynchronous threads?

I am trying to launch a function threaded using launch::async. However, I noticed that this doesn't work when passing struct elements as parameter:
The code

#include <future>
#include <vector>
#include <thread>

struct example { int ten; };

void threadFunction(int number, std::string hi) { 
   printf("%s Your number is %d\n", hi.c_str(), number + 1);
}

int main() {
   example ex;
   ex.ten = 9;
   std::string someString = "Hi there!";
   std::vector< std::future< void > > threads(5);
   for (uint16_t s = 0; s < 5; s += 1) {
      threads[s] = async(std::launch::async,
                                   [ex.ten,
                                   someString] {
         threadFunction(ex.ten, someString);
      });
   }
}

gives the following errors:

file.cpp: In function ‘int main()’:
file.cpp:25:39: error: expected ‘,’ before ‘.’ token
                                    [ex.ten,
                                       ^
file.cpp:25:39: error: expected identifier before ‘.’ token
file.cpp:25:43: error: expected ‘]’ before ‘,’ token
                                    [ex.ten,
                                           ^
file.cpp: In lambda function:
file.cpp:25:43: error: expected ‘{’ before ‘,’ token
file.cpp: In function ‘int main()’:
file.cpp:26:46: error: expected ‘)’ before ‘]’ token
                                    someString] {
                                              ^
file.cpp:28:8: error: expected primary-expression before ‘)’ token
       });

When replacing ex.ten with some other variable ten it does work.

So my questions are:
1. Why does launch::async not work with struct elements?
2. Is there a way to do it in a more elegant way than to make a variable for each element in the struct and pass those variables instead? (such as int ten = ex.ten; etc)

Aucun commentaire:

Enregistrer un commentaire