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