|
| 1 | +/* SPDX-License-Identifier: GPL-2.0-or-later */ |
| 2 | +/* |
| 3 | + * Copyright(c) 2025 John Sanpe <sanpeqf@gmail.com> |
| 4 | + */ |
| 5 | + |
| 6 | +#define MODULE_NAME "atomic-spinlock" |
| 7 | +#define bfdev_log_fmt(fmt) MODULE_NAME ": " fmt |
| 8 | + |
| 9 | +#include <bfdev/atomic.h> |
| 10 | +#include <bfdev/cmpxchg.h> |
| 11 | +#include <bfdev/log.h> |
| 12 | +#include <pthread.h> |
| 13 | +#include <unistd.h> |
| 14 | + |
| 15 | +static |
| 16 | +bfdev_atomic_t lock; |
| 17 | + |
| 18 | +static volatile |
| 19 | +long counter; |
| 20 | + |
| 21 | +static void |
| 22 | +spin_lock(bfdev_atomic_t *lock) |
| 23 | +{ |
| 24 | + while (bfdev_cmpxchg(lock, 1, 0) != 1) |
| 25 | + sched_yield(); |
| 26 | +} |
| 27 | + |
| 28 | +static void |
| 29 | +spin_unlock(bfdev_atomic_t *lock) |
| 30 | +{ |
| 31 | + if (bfdev_cmpxchg(lock, 0, 1) == 0) |
| 32 | + sched_yield(); |
| 33 | +} |
| 34 | + |
| 35 | +static void * |
| 36 | +thread1_task(void *unused) |
| 37 | +{ |
| 38 | + unsigned int time; |
| 39 | + |
| 40 | + for (time = 0; time < 1000000; ++time) { |
| 41 | + spin_lock(&lock); |
| 42 | + counter++; |
| 43 | + spin_unlock(&lock); |
| 44 | + } |
| 45 | + |
| 46 | + return NULL; |
| 47 | +} |
| 48 | + |
| 49 | +static void * |
| 50 | +thread2_task(void *unused) |
| 51 | +{ |
| 52 | + unsigned int time; |
| 53 | + |
| 54 | + for (time = 0; time < 1000000; ++time) { |
| 55 | + spin_lock(&lock); |
| 56 | + counter--; |
| 57 | + spin_unlock(&lock); |
| 58 | + } |
| 59 | + |
| 60 | + return NULL; |
| 61 | +} |
| 62 | + |
| 63 | +int |
| 64 | +main(int argc, const char *argv[]) |
| 65 | +{ |
| 66 | + pthread_t thread1, thread2; |
| 67 | + |
| 68 | + bfdev_atomic_write(&lock, 1); |
| 69 | + pthread_create(&thread1, NULL, thread1_task, NULL); |
| 70 | + pthread_create(&thread2, NULL, thread2_task, NULL); |
| 71 | + |
| 72 | + pthread_join(thread1, NULL); |
| 73 | + pthread_join(thread2, NULL); |
| 74 | + |
| 75 | + bfdev_log_info("counter: %ld\n", counter); |
| 76 | + if (counter) |
| 77 | + return 1; |
| 78 | + |
| 79 | + return 0; |
| 80 | +} |
0 commit comments