Skip to content

Instantly share code, notes, and snippets.

@HirbodBehnam
Created December 13, 2022 20:14
Show Gist options
  • Save HirbodBehnam/16ece47ec69b8d3d7e82f54c353b5cad to your computer and use it in GitHub Desktop.
Save HirbodBehnam/16ece47ec69b8d3d7e82f54c353b5cad to your computer and use it in GitHub Desktop.
Experimental semaphore with unix pipe
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