@@ -46,14 +46,15 @@ std::string makeTopic(const std::string& suffix) {
4646// / plus fully-read content. Registers itself as the topic's handler.
4747class TextStreamCollector {
4848public:
49+ ~TextStreamCollector () { recv_thread_.join (); }
4950 void registerOn (Room& room, const std::string& topic) {
5051 // Handlers run on the Room event thread and must not block (per
5152 // registerTextStreamHandler's docs), since later chunk/close events for
5253 // this same reader are dispatched on that same thread. readAll() blocks
5354 // until close, so it has to happen on a separate thread.
5455 room.registerTextStreamHandler (
5556 topic, [this ](std::shared_ptr<TextStreamReader> reader, const std::string& participant_identity) {
56- std::thread ([this , reader, participant_identity] {
57+ recv_thread_ = std::thread ([this , reader, participant_identity] {
5758 auto info = reader->info ();
5859 auto text = reader->readAll ();
5960 std::lock_guard<std::mutex> lock (mutex_);
@@ -62,7 +63,8 @@ class TextStreamCollector {
6263 sender_identity_ = participant_identity;
6364 done_ = true ;
6465 cv_.notify_all ();
65- }).detach ();
66+ });
67+ recv_thread_.detach ();
6668 });
6769 }
6870
@@ -76,6 +78,7 @@ class TextStreamCollector {
7678 const std::string& senderIdentity () const { return sender_identity_; }
7779
7880private:
81+ std::thread recv_thread_{};
7982 std::mutex mutex_;
8083 std::condition_variable cv_;
8184 bool done_ = false ;
@@ -87,12 +90,13 @@ class TextStreamCollector {
8790// / Same idea as TextStreamCollector, for byte streams.
8891class ByteStreamCollector {
8992public:
93+ ~ByteStreamCollector () { recv_thread_.join (); }
9094 void registerOn (Room& room, const std::string& topic) {
9195 // See TextStreamCollector::registerOn: the blocking readNext() loop must
9296 // not run on the Room event thread.
9397 room.registerByteStreamHandler (
9498 topic, [this ](std::shared_ptr<ByteStreamReader> reader, const std::string& participant_identity) {
95- std::thread ([this , reader, participant_identity] {
99+ recv_thread_ = std::thread ([this , reader, participant_identity] {
96100 auto info = reader->info ();
97101 std::vector<std::uint8_t > content;
98102 std::vector<std::uint8_t > chunk;
@@ -105,7 +109,8 @@ class ByteStreamCollector {
105109 sender_identity_ = participant_identity;
106110 done_ = true ;
107111 cv_.notify_all ();
108- }).detach ();
112+ });
113+ recv_thread_.detach ();
109114 });
110115 }
111116
@@ -119,6 +124,7 @@ class ByteStreamCollector {
119124 const std::string& senderIdentity () const { return sender_identity_; }
120125
121126private:
127+ std::thread recv_thread_{};
122128 std::mutex mutex_;
123129 std::condition_variable cv_;
124130 bool done_ = false ;
0 commit comments