Browse Source

updated examples with mutexes

tastytea 8 months ago
parent
commit
e51841fe20
Signed by: tastytea <tastytea@tastytea.de> GPG Key ID: 59346E0EA35C67E5
2 changed files with 24 additions and 9 deletions
  1. 13
    8
      examples/example09_streaming_api.cpp
  2. 11
    1
      examples/example13_easy_stream.cpp

+ 13
- 8
examples/example09_streaming_api.cpp View File

@@ -9,6 +9,7 @@
9 9
 #include <thread>
10 10
 #include <chrono>
11 11
 #include <memory>
12
+#include <mutex>
12 13
 #ifdef MASTODON_CPP
13 14
     #include "mastodon-cpp.hpp"
14 15
 #else
@@ -39,16 +40,20 @@ int main(int argc, char *argv[])
39 40
     std::uint8_t counter = 0;
40 41
     while (true)
41 42
     {
42
-        ++counter;
43
-        std::cout << answer;
44
-        answer.clear();
45
-        if (counter == 10)
43
+        std::this_thread::sleep_for(std::chrono::seconds(2));
44
+        if (ptr != nullptr)
46 45
         {
47
-            std::cerr << "Cancelling...\n";
48
-            ptr->cancel_stream();
49
-            break;
46
+            std::lock_guard<std::mutex> lock(ptr->get_mutex());
47
+            ++counter;
48
+            std::cout << answer;
49
+            answer.clear();
50
+            if (counter == 10)
51
+            {
52
+                std::cerr << "Cancelling...\n";
53
+                ptr->cancel_stream();
54
+                break;
55
+            }
50 56
         }
51
-        std::this_thread::sleep_for(std::chrono::seconds(2));
52 57
     }
53 58
     pub.join();
54 59
     std::cout << '\n';

+ 11
- 1
examples/example13_easy_stream.cpp View File

@@ -11,6 +11,7 @@
11 11
 #include <memory>
12 12
 #include <vector>
13 13
 #include <chrono>
14
+#include <mutex>
14 15
 
15 16
 // If we are compiling mastodon-cpp, use another include path
16 17
 #ifdef MASTODON_CPP
@@ -51,6 +52,16 @@ int main(int argc, char *argv[])
51 52
 
52 53
     while (true)
53 54
     {
55
+        std::this_thread::sleep_for(std::chrono::seconds(1));
56
+        // Skip iteration if ptr points not to the Mastodon::API::http object
57
+        if (ptr != nullptr)
58
+        {
59
+            continue;
60
+        }
61
+
62
+        // Acquire lock to for the stream variable
63
+        std::lock_guard<std::mutex> lock(ptr->get_mutex());
64
+
54 65
         // Parse event stream and clear it afterwards
55 66
         std::vector<Easy::stream_event> events = Easy::parse_stream(stream);
56 67
         stream.clear();
@@ -85,7 +96,6 @@ int main(int argc, char *argv[])
85 96
                     cout << "Something undefined happened. 😱\n";
86 97
             }
87 98
         }
88
-        std::this_thread::sleep_for(std::chrono::seconds(1));
89 99
     }
90 100
 
91 101
     pub_tl.join();

Loading…
Cancel
Save