c - Synchronising processes with semaphores -
i'm having tricky time understanding how alternate control between 2 processes using semaphores. here's contrived example of process handling code.
int pid = fork(); if (pid) { int counter = 0; while (true) { counter += 1; printf("p%d = %d", pid, counter); } } else { int counter = 0; while (true) { counter += 1; printf("p%d = %d", pid, counter); } }
i expecting above code run in parallel, seems control flow continues instantly forked process , later resumes parent process.
this fundamentally breaking existing code uses semaphore control process can act.
int id = get_semaphore(1); int pid = fork(); if (pid) { int counter = 0; while (true) { sem_wait(id); counter += 1; printf("p%d = %d\n", pid, counter); sem_signal(id); } } else { int counter = 0; while (true) { sem_wait(id); counter += 1; printf("p%d = %d\n", pid, counter); sem_signal(id); } }
the
sem_wait
helper subtracts 1 semaphore value , blocks until result > 0 (usessemop
under hood).the
sem_signal
helper adds 1 semaphore value (usessemop
under hood).
i'd code alternate between 2 processes, using sem_wait
block until other process releases resources sem_signal
. desired output be:
p1 = 0 p0 = 0 p1 = 1 p0 = 1 ...
however, because of initial execution delay between processes, child process takes available semaphore resource, uses print number, restores , loops — @ point resource available again, continues without ever waiting other process.
what's best way prevent process using resources if released them itself?
it seems control flow continues instantly forked process , later resumes parent process
that because stream io buffers output on stdout
until either
- the buffer full
fflush()
called onstdout
- a newline (
\n
) encountered
in program, each process fill buffer before sending contents stdout
giving appearance of 1 process running long time, other. terminate format strings of printf
statements \n
, you'll see behaviour in first program more expect.
i not sure why semaphore thing isn't working - i'm not knowledgeable system v semaphores seems red flag me getting semaphore after have forked. more common posix semaphores, semaphore has in memory both processes can see otherwise it's 2 semaphores.
anyway, assuming get_semaphore()
function right thing share semaphore, there still problem because there no guarantee that, when 1 process signals semaphore, other 1 start enough grab again before first process loops round , grabs itself.
you need 2 semaphores, 1 parent , 1 child. before print each process should wait on own semaphore. after print, each process should signal other semaphore. also, 1 semaphore should initialised count of 1 , other should initialised count of 0.
Comments
Post a Comment