Skip to content

Commit 74d61fe

Browse files
povergoingstephanosio
authored andcommitted
tests: kernel: semaphore: sys_sem: Fix coherence issue
The issue is caused by multiple threads which have taken the semaphore to increase or decrease the normal count variable. Change its type with atomic_t. Signed-off-by: Jaxson Han <[email protected]>
1 parent 933a8f9 commit 74d61fe

File tree

1 file changed

+11
-5
lines changed
  • tests/kernel/semaphore/sys_sem/src

1 file changed

+11
-5
lines changed

tests/kernel/semaphore/sys_sem/src/main.c

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ static struct k_thread multi_tid_give[STACK_NUMS];
2424
static struct k_thread multi_tid_take[STACK_NUMS];
2525
static struct k_sem usage_sem, sync_sem, limit_sem, uninit_sem;
2626
static ZTEST_DMEM int flag;
27-
static ZTEST_DMEM int count;
27+
static ZTEST_DMEM atomic_t atomic_count;
2828

2929
/**
3030
* @defgroup kernel_sys_sem_tests Semaphore
@@ -127,7 +127,10 @@ void test_multiple_thread_sem_usage(void)
127127

128128
static void multi_thread_sem_give(void *p1, void *p2, void *p3)
129129
{
130-
count++;
130+
int count;
131+
132+
(void)atomic_inc(&atomic_count);
133+
count = atomic_get(&atomic_count);
131134
k_sem_give(&limit_sem);
132135

133136
if (count < TOTAL_MAX)
@@ -140,8 +143,11 @@ static void multi_thread_sem_give(void *p1, void *p2, void *p3)
140143

141144
static void multi_thread_sem_take(void *p1, void *p2, void *p3)
142145
{
146+
int count;
147+
143148
k_sem_take(&limit_sem, K_FOREVER);
144-
count--;
149+
(void)atomic_dec(&atomic_count);
150+
count = atomic_get(&atomic_count);
145151

146152
if (count >= 0)
147153
zassert_equal(k_sem_count_get(&limit_sem), count, "multi take sem error");
@@ -167,7 +173,7 @@ void test_multi_thread_sem_limit(void)
167173
k_sem_init(&limit_sem, SEM_INIT_VAL, SEM_MAX_VAL);
168174
k_sem_init(&sync_sem, SEM_INIT_VAL, SEM_MAX_VAL);
169175

170-
count = 0;
176+
(void)atomic_set(&atomic_count, 0);
171177
for (int i = 1; i <= TOTAL_MAX; i++) {
172178
k_thread_create(&multi_tid_give[i], multi_stack_give[i], STACK_SIZE,
173179
multi_thread_sem_give, NULL, NULL, NULL,
@@ -176,7 +182,7 @@ void test_multi_thread_sem_limit(void)
176182

177183
k_sleep(K_MSEC(50));
178184

179-
count = SEM_MAX_VAL;
185+
(void)atomic_set(&atomic_count, SEM_MAX_VAL);
180186
for (int i = 1; i <= TOTAL_MAX; i++) {
181187
k_thread_create(&multi_tid_take[i], multi_stack_take[i], STACK_SIZE,
182188
multi_thread_sem_take, NULL, NULL, NULL,

0 commit comments

Comments
 (0)