Created
December 13, 2022 20:14
-
-
Save HirbodBehnam/16ece47ec69b8d3d7e82f54c353b5cad to your computer and use it in GitHub Desktop.
Experimental semaphore with unix pipe
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typedef struct { | |
int reader; | |
int writer; | |
} semaphore; | |
semaphore make_semaphore(int n) { | |
int pipe_fd[2]; | |
pipe(pipe_fd); | |
semaphore result = { | |
.reader = pipe_fd[0], | |
.writer = pipe_fd[1], | |
}; | |
// Write to pipe | |
char c; | |
while (n--) | |
write(result.writer, &c, sizeof(c)); | |
return result; | |
} | |
void semaphore_acquire(semaphore *s) { | |
char c; | |
read(s->reader, &c, sizeof(c)); | |
} | |
void semaphore_release(semaphore *s) { | |
char c; | |
write(s->writer, &c, sizeof(c)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment