mirror of
https://github.com/switchbrew/libnx.git
synced 2025-08-06 00:19:22 +02:00
barrier implementation using semaphores (#186)
This commit is contained in:
parent
318562d13b
commit
b130d96445
@ -34,6 +34,7 @@ extern "C" {
|
||||
#include "switch/kernel/random.h"
|
||||
#include "switch/kernel/jit.h"
|
||||
#include "switch/kernel/ipc.h"
|
||||
#include "switch/kernel/barrier.h"
|
||||
|
||||
#include "switch/services/sm.h"
|
||||
#include "switch/services/smm.h"
|
||||
|
30
nx/include/switch/kernel/barrier.h
Normal file
30
nx/include/switch/kernel/barrier.h
Normal file
@ -0,0 +1,30 @@
|
||||
/**
|
||||
* @file barrier.h
|
||||
* @brief Multi-threading Barrier
|
||||
* @author tatehaga
|
||||
* @copyright libnx Authors
|
||||
*/
|
||||
#pragma once
|
||||
#include "semaphore.h"
|
||||
|
||||
/// Barrier structure.
|
||||
typedef struct Barrier {
|
||||
u64 count; ///< Number of threads to reach the barrier.
|
||||
u64 thread_total; ///< Number of threads to wait on.
|
||||
Semaphore throttle; ///< Semaphore to make sure threads release to scheduler one at a time.
|
||||
Semaphore lock; ///< Semaphore to lock barrier to prevent multiple operations by threads at once.
|
||||
Semaphore thread_wait; ///< Semaphore to force a thread to wait if count < thread_total.
|
||||
} Barrier;
|
||||
|
||||
/**
|
||||
* @brief Initializes a barrier and the number of threads to wait on.
|
||||
* @param b Barrier object.
|
||||
* @param thread_count Initial value for the number of threads the barrier must wait for.
|
||||
*/
|
||||
void barrierInit(Barrier *b, u64 thread_count);
|
||||
|
||||
/**
|
||||
* @brief Forces threads to wait until all threads have called barrierWait.
|
||||
* @param b Barrier object.
|
||||
*/
|
||||
void barrierWait(Barrier *b);
|
29
nx/source/kernel/barrier.c
Normal file
29
nx/source/kernel/barrier.c
Normal file
@ -0,0 +1,29 @@
|
||||
#include "kernel/barrier.h"
|
||||
|
||||
void barrierInit(Barrier *b, u64 thread_count) {
|
||||
b->count = 0;
|
||||
b->thread_total = thread_count;
|
||||
semaphoreInit(&b->throttle, 0);
|
||||
semaphoreInit(&b->lock, 1);
|
||||
semaphoreInit(&b->thread_wait, 0);
|
||||
}
|
||||
|
||||
void barrierWait(Barrier *b) {
|
||||
semaphoreWait(&b->lock);
|
||||
if(b->count < b->thread_total) {
|
||||
b->count++;
|
||||
}
|
||||
if(b->count < b->thread_total) {
|
||||
semaphoreSignal(&b->lock);
|
||||
semaphoreWait(&b->thread_wait);
|
||||
semaphoreSignal(&b->throttle);
|
||||
}
|
||||
else if(b->count == b->thread_total) {
|
||||
for(int i = 0; i < b->thread_total-1; i++) {
|
||||
semaphoreSignal(&b->thread_wait);
|
||||
semaphoreWait(&b->throttle);
|
||||
}
|
||||
b->count = 0;
|
||||
semaphoreSignal(&b->lock);
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user