]> Creatis software - cpPlugins.git/blob - appli/examples/example_Test_async.cxx
merge async example
[cpPlugins.git] / appli / examples / example_Test_async.cxx
1 #include <future>
2 #include <iostream>
3 #ifdef WIN32
4 #include <windows.h>
5 #else
6 #endif
7
8 #ifdef WIN32
9 #define mysleep Sleep(2000);
10 #else
11 #define mysleep usleep(2000);
12 #endif
13
14 class Test
15 {
16 private:
17   std::vector<int> state;
18   std::vector<int>::iterator it;
19   std::vector<bool> isAvailable;
20 public:
21   Test()
22   {
23     this->it = this->state.begin();
24   }
25
26   void called_from_async()
27   {
28
29     std::cout << "called from async" << std::endl;
30     this->state.insert(this->it ,10);
31   }
32
33   std::string returned_from_async() {
34     mysleep;
35     return "Async call";
36   }
37
38   template<class ASYNC>
39   void print_results(ASYNC &f)
40   {
41     std::string result = f.get();
42     std::cout << result.c_str() << std::endl;
43   }
44
45   int getState(int pos)
46   {
47     return this->state.at(pos);
48   }
49
50   int getStateSize()
51   {
52     return this->state.size();
53   }
54 };
55
56 int main() {
57   Test test;
58   std::future<void> result(std::async(&Test::called_from_async, &test));
59
60   auto f1 = std::async(std::launch::async, &Test::returned_from_async, &test);
61  
62   std::cout << "Message from main." << std::endl;
63   do
64   {
65     std::cout << test.getStateSize();
66   } while (test.getStateSize()<1);
67
68 #ifdef _DEBUG
69   auto i = 0;
70   std::cout << "wait for close";
71   std::cin >> i;
72 #endif
73
74   return 0;
75
76 }