Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ add_subdirectory(allocator)
add_subdirectory(arc4)
add_subdirectory(array)
add_subdirectory(ascii85)
add_subdirectory(atomic)
add_subdirectory(base32)
add_subdirectory(base64)
add_subdirectory(bfdev)
Expand Down
2 changes: 2 additions & 0 deletions examples/atomic/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# SPDX-License-Identifier: GPL-2.0-or-later
/atomic-spinlock
22 changes: 22 additions & 0 deletions examples/atomic/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# SPDX-License-Identifier: GPL-2.0-or-later
#
# Copyright(c) 2023 John Sanpe <sanpeqf@gmail.com>
#

add_executable(atomic-spinlock spinlock.c)
target_link_libraries(atomic-spinlock bfdev)
add_test(atomic-spinlock atomic-spinlock)

if(${CMAKE_PROJECT_NAME} STREQUAL "bfdev")
install(FILES
spinlock.c
DESTINATION
${CMAKE_INSTALL_DOCDIR}/examples/atomic
)

install(TARGETS
atomic-spinlock
DESTINATION
${CMAKE_INSTALL_DOCDIR}/bin
)
endif()
80 changes: 80 additions & 0 deletions examples/atomic/spinlock.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */
/*
* Copyright(c) 2025 John Sanpe <sanpeqf@gmail.com>
*/

#define MODULE_NAME "atomic-spinlock"
#define bfdev_log_fmt(fmt) MODULE_NAME ": " fmt

#include <bfdev/atomic.h>
#include <bfdev/cmpxchg.h>
#include <bfdev/log.h>
#include <pthread.h>
#include <unistd.h>

static
bfdev_atomic_t lock;

static volatile
long counter;

static void
spin_lock(bfdev_atomic_t *lock)
{
while (bfdev_cmpxchg(lock, 1, 0) != 1)
sched_yield();
}

static void
spin_unlock(bfdev_atomic_t *lock)
{
if (bfdev_cmpxchg(lock, 0, 1) == 0)
sched_yield();
}

static void *
thread1_task(void *unused)
{
unsigned int time;

for (time = 0; time < 1000000; ++time) {
spin_lock(&lock);
counter++;
spin_unlock(&lock);
}

return NULL;
}

static void *
thread2_task(void *unused)
{
unsigned int time;

for (time = 0; time < 1000000; ++time) {
spin_lock(&lock);
counter--;
spin_unlock(&lock);
}

return NULL;
}

int
main(int argc, const char *argv[])
{
pthread_t thread1, thread2;

bfdev_atomic_write(&lock, 1);
pthread_create(&thread1, NULL, thread1_task, NULL);
pthread_create(&thread2, NULL, thread2_task, NULL);

pthread_join(thread1, NULL);
pthread_join(thread2, NULL);

bfdev_log_info("counter: %ld\n", counter);
if (counter)
return 1;

return 0;
}
Loading