ciabatta/tests/threaded.c

42 lines
1002 B
C
Raw Normal View History

2023-08-15 08:54:02 +00:00
#include <stdio.h>
#include <stdlib.h>
#include <threads.h>
2023-08-26 11:35:18 +00:00
#include <stdatomic.h>
2023-08-27 02:51:35 +00:00
#include <cia/sync.h>
2023-08-15 08:54:02 +00:00
2023-08-27 02:51:35 +00:00
static Cia_Mutex g_mutex;
static volatile i64 counter = 0;
2023-08-26 07:28:59 +00:00
2023-08-15 08:54:02 +00:00
int thrd_func(void *arg) {
printf("child thread: ok!\n");
2023-08-26 07:28:59 +00:00
for(int i = 0; i < 100000; ++i) {
2023-08-27 02:51:35 +00:00
cia_mutex_lock(&g_mutex);
2023-08-26 07:28:59 +00:00
counter += 1;
2023-08-27 02:51:35 +00:00
cia_mutex_unlock(&g_mutex);
2023-08-26 07:28:59 +00:00
}
printf("child thread: counter = %I64d\n", counter);
2023-08-15 08:54:02 +00:00
return 0;
}
int main() {
printf("main thread: before\n");
2023-08-27 02:51:35 +00:00
cia_mutex_init(&g_mutex);
2023-08-15 08:54:02 +00:00
thrd_t thrd;
2023-08-26 07:28:59 +00:00
int status = thrd_create(&thrd, thrd_func, NULL);
if(status == thrd_error) {
printf("main thread: error creating child thread\n");
2023-08-26 07:28:59 +00:00
return 1;
}
printf("main thread: after!\n");
2023-08-26 07:28:59 +00:00
for(int i = 0; i < 100000; ++i) {
2023-08-27 02:51:35 +00:00
cia_mutex_lock(&g_mutex);
2023-08-26 07:28:59 +00:00
counter += 1;
2023-08-27 02:51:35 +00:00
cia_mutex_unlock(&g_mutex);
}
2023-09-06 09:37:30 +00:00
int exit_code;
thrd_join(thrd, &exit_code);
printf("main thread: counter = %I64d\n", counter);
2023-08-15 08:54:02 +00:00
return 0;
}