Handout: POSIX Semaphores Example
semex.c / semworker.c à in /data/htdocs/cs644(class webpage home)
-- work on both Solaris & Linux 2.6
-- create n processes
-- use semaphore for mutex
-- usual pattern: original process – create sem
forks: child process
child process: do “work” (coordinated by mutex)
2 cases: -- no coordination ( USE_SHARED_MEMORY not defined)
TTThhh…… worker processes outputting at same time
-- with good coordination: ( USE_SHARED_MEMORY defined)
one process at a time outputs
This is process 28754.
This is process 28755.
...
Shared memory is memory available and usable to more than one process.
On Xinu, global variables represent shared memory, since they are usable from all processes. Local variables (i.e., automatic variables), however, are private to each process.
On UNIX/Linux (also on Windows), each process gets its own VA space (i.e., address space), separate from all other processes. Thus by default, after a fork, the two resulting processes have no shared memory.
To obtain shared memory, processes must use shared memory system calls to set up shared memory. In semex.c, we see:
· the shmget syscall used to allocate just enough shared memory to hold the crucial sem_t object that represents the semaphore state.
· the shmat syscall used to attach the allocated shared memory to the current address space. It returns the address where this process can see the shared memory in its address space. In general, different processes may see the same shared memory in different locations, like DLLs.
In semex.c, when shared memory is not in use, the fork copies the sem_t struct into private copies in the workers, that then each have their own semaphore, and there is no process coordination. When shared memory is in use, they share the same sem_t structure and actively coordinate with the semaphore.