summaryrefslogtreecommitdiffstats
path: root/src/fluent-bit/lib/wasm-micro-runtime-WAMR-1.2.2/core/iwasm/libraries/lib-wasi-threads/test/global_lock.c
blob: f81fca49b90ceb593b1c65df49fe544bd1abb633 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
 * Copyright (C) 2023 Amazon.com Inc. or its affiliates. All rights reserved.
 * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
 */

#ifndef __wasi__
#error This example only compiles to WASM/WASI target
#endif

#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <stdbool.h>

#if USE_CUSTOM_SYNC_PRIMITIVES != 0
#include "sync_primitives.h"
#else
#include <pthread.h>
#endif

#include "wasi_thread_start.h"

enum CONSTANTS {
    NUM_THREADS = 4,
    NUM_ITER = 200,
    SECOND = 1000 * 1000 * 1000, /* 1 second */
    TIMEOUT = 10LL * SECOND
};

pthread_mutex_t mutex;
int g_count = 0;

typedef struct {
    start_args_t base;
    int th_done;
} shared_t;

void
__wasi_thread_start_C(int thread_id, int *start_arg)
{
    shared_t *data = (shared_t *)start_arg;

    for (int i = 0; i < NUM_ITER; i++) {
        pthread_mutex_lock(&mutex);
        g_count++;
        pthread_mutex_unlock(&mutex);
    }

    __atomic_store_n(&data->th_done, 1, __ATOMIC_SEQ_CST);
    __builtin_wasm_memory_atomic_notify(&data->th_done, 1);
}

int
main(int argc, char **argv)
{
    shared_t data[NUM_THREADS] = { 0 };
    int thread_ids[NUM_THREADS];

    assert(pthread_mutex_init(&mutex, NULL) == 0 && "Failed to init mutex");

    for (int i = 0; i < NUM_THREADS; i++) {
        assert(start_args_init(&data[i].base));
        thread_ids[i] = __wasi_thread_spawn(&data[i]);
        assert(thread_ids[i] > 0 && "Thread creation failed");
    }

    printf("Wait for threads to finish\n");
    for (int i = 0; i < NUM_THREADS; i++) {
        if (__builtin_wasm_memory_atomic_wait32(&data[i].th_done, 0, TIMEOUT)
            == 2) {
            assert(false && "Wait should not time out");
        }

        start_args_deinit(&data[i].base);
    }

    printf("Value of count after update: %d\n", g_count);
    assert(g_count == (NUM_THREADS * NUM_ITER)
           && "Global count not updated correctly");

    assert(pthread_mutex_destroy(&mutex) == 0 && "Failed to destroy mutex");
    return EXIT_SUCCESS;
}