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