Advertisement
Guest User

Untitled

a guest
Aug 17th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.95 KB | None | 0 0
  1. //
  2. // Created by Andrew Cox 2017.
  3. //
  4.  
  5. #include <iostream>
  6. #include <future>
  7.  
  8. #include <stlab/concurrency/default_executor.hpp>
  9. #include <stlab/concurrency/future.hpp>
  10.  
  11. struct SharedState
  12. {
  13. int counter1;
  14. };
  15.  
  16. void spawn(SharedState& inOut)
  17. {
  18. // stlab::async won't accept this:
  19. auto taskNonConst = [] (int i, long double f, SharedState& inOut) -> SharedState&
  20. {
  21. inOut.counter1 = i * f;
  22. return inOut;
  23. };
  24.  
  25. // stlab::async won't accept this:
  26. auto taskNonConst_02_no_return = [] (int i, long double f, SharedState& inOut)
  27. {
  28. inOut.counter1 = i * f;
  29. };
  30.  
  31. const int i = rand() & 0xff;
  32. const long double f = rand() / double(RAND_MAX);
  33.  
  34. // Direct calls work fine:
  35. auto& direct = taskNonConst(i, f, inOut);
  36. taskNonConst_02_no_return(i, f, inOut);
  37.  
  38. // Non-const references fail to compile, even using std::ref():
  39.  
  40. auto stdFuture1 = std::async(std::launch::async, taskNonConst, i, f, std::ref(inOut)); // Compiles [expect: compile as std::ref used]
  41. //auto stdFuture2 = std::async(std::launch::async, taskNonConst, i, f, inOut); // Fails [expect: fail as non-const ref not allowed for async]
  42. auto stlabFuture1 = stlab::async(stlab::default_executor, taskNonConst, i, f, std::ref(inOut)); // Fail [expect: compile as std::ref used]
  43. //auto stlabFuture2 = stlab::async(stlab::default_executor, taskNonConst, i, f, inOut); // Fails [expect: fail as non-const ref not allowed]
  44.  
  45. auto stdFutureNoRet1 = std::async(std::launch::async, taskNonConst_02_no_return, i, f, std::ref(inOut));
  46. auto stlabFutureNoRet1 = stlab::async(stlab::default_executor, taskNonConst_02_no_return, i, f, std::ref(inOut)); // Fails
  47.  
  48.  
  49. while(!stlabFutureNoRet1.get_try()) {
  50. std::this_thread::yield();
  51. }
  52. }
  53.  
  54. int main()
  55. {
  56. SharedState inOut { 0 };
  57.  
  58. spawn(inOut);
  59.  
  60. // Prevent dead code elimination:
  61. auto result = inOut.counter1;
  62. std::cout << "result = " << result << std::endl;
  63.  
  64. return result <= 0.0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement