1414
1515#include " BlackboxTests.hpp"
1616
17- #include < atomic>
1817#include < memory>
18+ #include < mutex>
1919
2020#include < fastdds/dds/core/policy/ParameterTypes.hpp>
2121#include < fastdds/dds/topic/TypeSupport.hpp>
@@ -315,7 +315,9 @@ TEST(KeyedTopic, key_only_payload)
315315 if (payload.is_serialized_key )
316316 {
317317 // Count the number of times compute_key is called with a key-only payload
318- key_only_payload_count++;
318+ std::lock_guard<std::mutex> lock (mtx_);
319+ key_only_payload_count_++;
320+ cv_.notify_all ();
319321 }
320322
321323 return KeyedHelloWorldPubSubType::compute_key (payload, ihandle, force_md5);
@@ -329,7 +331,27 @@ TEST(KeyedTopic, key_only_payload)
329331 return KeyedHelloWorldPubSubType::compute_key (data, ihandle, force_md5);
330332 }
331333
332- std::atomic<uint32_t > key_only_payload_count{ 0 };
334+ uint32_t nb_of_times_called_with_key_only_payload () const
335+ {
336+ std::lock_guard<std::mutex> lock (mtx_);
337+ return key_only_payload_count_;
338+ }
339+
340+ void wait_for_key_only_payload (
341+ std::uint32_t min_value)
342+ {
343+ std::unique_lock<std::mutex> lock (mtx_);
344+ cv_.wait (lock, [this , min_value]()
345+ {
346+ return key_only_payload_count_ >= min_value;
347+ });
348+ }
349+
350+ private:
351+
352+ mutable std::mutex mtx_;
353+ std::condition_variable cv_;
354+ std::uint32_t key_only_payload_count_ = 0 ;
333355 };
334356
335357 // Force using UDP transport
@@ -368,7 +390,7 @@ TEST(KeyedTopic, key_only_payload)
368390 // Check that compute_key was not called with a key-only payload when KEY_HASH is present
369391 auto ts = std::dynamic_pointer_cast<TestTypeSupport>(reader.get_type_support ());
370392 ASSERT_TRUE (ts != nullptr );
371- EXPECT_EQ (ts->key_only_payload_count . load (), 0u );
393+ EXPECT_EQ (ts->nb_of_times_called_with_key_only_payload (), 0u );
372394
373395 struct KeyOnlyPayloadPacket
374396 {
@@ -428,10 +450,7 @@ TEST(KeyedTopic, key_only_payload)
428450 }
429451
430452 // Wait for key-only compute key to be called
431- while (ts->key_only_payload_count .load () <= 0 )
432- {
433- std::this_thread::sleep_for (std::chrono::milliseconds (10 ));
434- }
453+ ts->wait_for_key_only_payload (1 );
435454}
436455
437456/* Uncomment when DDS API supports NO_WRITERS_ALIVE
0 commit comments