philosophers_prep/subjects/13_semaphore_basics.txt

29 lines
1.4 KiB
Plaintext

Assignment name: semaphore_basics
Expected files: semaphore_basics.c
Allowed functions: memset, printf, malloc, free, write, fork, exit, waitpid,
sem_open, sem_close, sem_post, sem_wait, sem_unlink,
usleep, gettimeofday
-------------------------------------------------------------------------------
Create a program that demonstrates POSIX semaphores:
1. Create a named semaphore initialized to 3 (simulating 3 available resources)
2. Launch 5 child processes
3. Each child process tries to acquire a resource (sem_wait), uses it for 500ms, then releases it (sem_post)
4. Each child prints when it acquires and releases a resource
5. Parent waits for all children to finish
6. Properly cleanup the semaphore using sem_unlink()
Output format:
- "Child <id> (PID: <pid>): Waiting for resource..."
- "Child <id> (PID: <pid>): Acquired resource (available: <count>)"
- "Child <id> (PID: <pid>): Using resource..."
- "Child <id> (PID: <pid>): Released resource"
Usage: `./semaphore_basics`
Hint: Named POSIX semaphores (sem_open) work across processes, unlike thread mutexes.
sem_wait() decrements the semaphore (blocks if 0), sem_post() increments it.
Always call sem_unlink() to remove the semaphore from the system.
Semaphore names must start with '/' (e.g., "/my_semaphore").
Use O_CREAT | O_EXCL flags with sem_open, and handle if semaphore already exists.