2023-10-21 21:23:51 +03:00
|
|
|
|
/**
|
|
|
|
|
* lock.c
|
|
|
|
|
* Функции блокировок
|
|
|
|
|
*
|
|
|
|
|
* Функционал блокировок и синхронизации
|
|
|
|
|
*
|
|
|
|
|
*/
|
|
|
|
|
|
2023-10-07 18:28:48 +03:00
|
|
|
|
#include <fb.h>
|
|
|
|
|
#include <lock.h>
|
2024-01-13 00:00:11 +03:00
|
|
|
|
#include <log.h>
|
2023-10-07 18:28:48 +03:00
|
|
|
|
#include <stdint.h>
|
|
|
|
|
#include <tool.h>
|
|
|
|
|
|
2023-10-24 23:39:00 +03:00
|
|
|
|
// Если не заблокировано - блокируем
|
2023-10-21 20:27:23 +03:00
|
|
|
|
int lock_swap(lock_t *lock) {
|
2023-10-07 18:28:48 +03:00
|
|
|
|
return __sync_bool_compare_and_swap(&lock->lock, 0, 1);
|
|
|
|
|
}
|
|
|
|
|
|
2023-10-24 23:39:00 +03:00
|
|
|
|
// Запрос блокировки ресурса
|
2023-10-21 20:27:23 +03:00
|
|
|
|
void lock_acquire(lock_t *lock) {
|
2023-10-07 18:28:48 +03:00
|
|
|
|
uint64_t count = 0;
|
|
|
|
|
|
|
|
|
|
for (;;) {
|
2023-10-21 20:27:23 +03:00
|
|
|
|
if (lock_swap(lock)) { break; }
|
2023-10-07 18:28:48 +03:00
|
|
|
|
count++;
|
|
|
|
|
if (count > 1000000) {
|
2023-10-29 16:12:00 +03:00
|
|
|
|
LOG("%s блокировка зависла", lock->file);
|
2023-10-07 18:28:48 +03:00
|
|
|
|
assert(0);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
asm volatile("pause");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-10-24 23:39:00 +03:00
|
|
|
|
// Запрос разблокировки ресурса
|
2023-10-21 20:27:23 +03:00
|
|
|
|
void lock_release(lock_t *lock) {
|
2023-10-07 18:28:48 +03:00
|
|
|
|
__sync_bool_compare_and_swap(&lock->lock, 1, 0);
|
2023-10-21 20:27:23 +03:00
|
|
|
|
}
|