Skip to content

Commit f225ef6

Browse files
authored
Merge pull request #62 from seanwevans/codex/refactor-acquire_semaphore-for-atomic-updates
Ensure semaphore acquisition is atomic
2 parents 9be4983 + 8c2bb87 commit f225ef6

1 file changed

Lines changed: 11 additions & 4 deletions

File tree

pg_os--1.0.sql

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -528,17 +528,24 @@ GRANT EXECUTE ON FUNCTION create_semaphore(TEXT, INTEGER, INTEGER) TO PUBLIC;
528528
-- acquire a semaphore. If count is 0, the process must wait
529529
CREATE OR REPLACE FUNCTION acquire_semaphore(process_id INTEGER, sem_name TEXT) RETURNS VOID AS $$
530530
DECLARE
531-
sem RECORD;
531+
acquired_sem_id INTEGER;
532532
BEGIN
533-
SELECT * INTO sem FROM semaphores WHERE name = sem_name;
533+
-- Ensure the semaphore exists before attempting acquisition
534+
PERFORM 1 FROM semaphores WHERE name = sem_name;
534535

535536
IF NOT FOUND THEN
536537
RAISE EXCEPTION 'Semaphore % not found', sem_name;
537538
END IF;
538539

539-
IF sem.count > 0 THEN
540+
-- Attempt to atomically decrement the semaphore count.
541+
UPDATE semaphores
542+
SET count = count - 1
543+
WHERE name = sem_name
544+
AND count > 0
545+
RETURNING id INTO acquired_sem_id;
546+
547+
IF FOUND THEN
540548
-- Acquire the semaphore immediately
541-
UPDATE semaphores SET count = count - 1 WHERE name = sem_name;
542549
UPDATE processes SET waiting_on_semaphore = NULL WHERE id = process_id;
543550
PERFORM log_process_action(process_id, 'Semaphore acquired: ' || sem_name);
544551
ELSE

0 commit comments

Comments
 (0)