Use shared memory lock for threads generated from same module (#1960)

Multiple threads generated from the same module should use the same
lock to protect the atomic operations.

Before this PR, each thread used a different lock to protect atomic
operations (e.g. atomic add), making the lock ineffective.

Fix #1958.
This commit is contained in:
Enrico Loparco
2023-02-16 04:54:19 +01:00
committed by GitHub
parent 1c17665f68
commit 216dc43ab4
11 changed files with 203 additions and 146 deletions

View File

@ -41,3 +41,6 @@ target_link_libraries(test.wasm)
add_executable(main_thread_exception.wasm main_thread_exception.c)
target_link_libraries(main_thread_exception.wasm)
add_executable(main_global_atomic.wasm main_global_atomic.c)
target_link_libraries(main_global_atomic.wasm)

View File

@ -0,0 +1,48 @@
/*
* Copyright (C) 2023 Amazon.com Inc. or its affiliates. All rights reserved.
* SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
*/
#include <stdio.h>
#include <pthread.h>
#define MAX_NUM_THREADS 4
#define NUM_ITER 1000
int g_count = 0;
static void *
thread(void *arg)
{
for (int i = 0; i < NUM_ITER; i++) {
__atomic_fetch_add(&g_count, 1, __ATOMIC_SEQ_CST);
}
return NULL;
}
int
main(int argc, char **argv)
{
pthread_t tids[MAX_NUM_THREADS];
for (int i = 0; i < MAX_NUM_THREADS; i++) {
if (pthread_create(&tids[i], NULL, thread, NULL) != 0) {
printf("Thread creation failed\n");
}
}
for (int i = 0; i < MAX_NUM_THREADS; i++) {
if (pthread_join(tids[i], NULL) != 0) {
printf("Thread join failed\n");
}
}
printf("Value of counter after update: %d (expected=%d)\n", g_count,
MAX_NUM_THREADS * NUM_ITER);
if (g_count != MAX_NUM_THREADS * NUM_ITER) {
__builtin_trap();
}
return -1;
}