Skip to content

Commit 5f495db

Browse files
kjbraceybulislaw
authored andcommitted
Robustify equeue multithread test
Rather than wait 10ms before breaking the other thread, and expecting at least one event to have been run, wait for one event to be run, then break. Should avoid some spurious failures that have been seen.
1 parent 50455c0 commit 5f495db

File tree

1 file changed

+59
-8
lines changed

1 file changed

+59
-8
lines changed

UNITTESTS/events/equeue/test_equeue.cpp

Lines changed: 59 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -139,11 +139,64 @@ static void *multithread_thread(void *p)
139139
return 0;
140140
}
141141

142+
class ecount {
143+
mutable pthread_mutex_t mutex;
144+
pthread_cond_t cond;
145+
uint8_t count;
146+
public:
147+
ecount() : count(0)
148+
{
149+
int err = pthread_mutex_init(&mutex, NULL);
150+
EXPECT_EQ(0, err);
151+
err = pthread_cond_init(&cond, NULL);
152+
EXPECT_EQ(0, err);
153+
}
154+
155+
~ecount()
156+
{
157+
int err = pthread_mutex_destroy(&mutex);
158+
EXPECT_EQ(0, err);
159+
err = pthread_cond_destroy(&cond);
160+
EXPECT_EQ(0, err);
161+
}
162+
163+
void lock() const
164+
{
165+
int err = pthread_mutex_lock(&mutex);
166+
EXPECT_EQ(0, err);
167+
}
168+
169+
void unlock() const
170+
{
171+
int err = pthread_mutex_unlock(&mutex);
172+
EXPECT_EQ(0, err);
173+
}
174+
175+
void touch()
176+
{
177+
lock();
178+
if (count < 200) {
179+
count++;
180+
}
181+
unlock();
182+
int err = pthread_cond_broadcast(&cond);
183+
EXPECT_EQ(0, err);
184+
}
185+
186+
void wait_for_touches(uint8_t n)
187+
{
188+
lock();
189+
while (count < n) {
190+
int err = pthread_cond_wait(&cond, &mutex);
191+
EXPECT_EQ(0, err);
192+
}
193+
unlock();
194+
}
195+
};
196+
142197
static void multithread_func(void *p)
143198
{
144-
if ((*(reinterpret_cast<uint8_t *>(p))) < 200) {
145-
(*(reinterpret_cast<uint8_t *>(p)))++;
146-
}
199+
static_cast<ecount *>(p)->touch();
147200
}
148201

149202
static void background_func(void *p, int ms)
@@ -665,20 +718,18 @@ TEST_F(TestEqueue, test_equeue_multithread)
665718
int err = equeue_create(&q, TEST_EQUEUE_SIZE);
666719
ASSERT_EQ(0, err);
667720

668-
uint8_t touched = 0;
669-
equeue_call_every(&q, 1, multithread_func, &touched);
721+
ecount t;
722+
equeue_call_every(&q, 1, multithread_func, &t);
670723

671724
pthread_t thread;
672725
err = pthread_create(&thread, 0, multithread_thread, &q);
673726
ASSERT_EQ(0, err);
674727

675-
usleep(10000);
728+
t.wait_for_touches(1);
676729
equeue_break(&q);
677730
err = pthread_join(thread, 0);
678731
ASSERT_EQ(0, err);
679732

680-
EXPECT_TRUE(touched > 1);
681-
682733
equeue_destroy(&q);
683734
}
684735

0 commit comments

Comments
 (0)