简体   繁体   中英

Alternatives to POSIX semaphores for 64-bit/32-bit IPC?

I need to implement some sort of blocking wait for a project requiring synchronization between 64-bit and 32-bit processes. Busy waiting on a shared memory variable introduces performance/scheduling issues and POSIX semaphores do not appear to support IPC between 32-bit and 64-bit processes. Are there other low-overhead alternatives for interprocess synchronization on Linux?

For inter-process synchronization using blocking waits, simple solutions include either a named pipe (fd) or a System V Semaphore .

Named pipes have a file path associated with them, so that the two processes can open the file independently (one for read, the other for write). For pure synchronization, just putc() to signal, and getc() to wait, one character at a time (value doesn't matter). This creates a unidirectional ("half duplex") channel; for bidirectional signal/waits you'd create two files. You can even queue up multiple signals by performing many putc() calls in a row, kind of like a semaphore which never saturates.

System V Semaphores also have a file path associated with them. These behave like a Dijkstra semaphore.

For additional options, check out

https://en.wikipedia.org/wiki/Inter-process_communication

Linux has futexes which are a kernel primitive that provides a way for one process to go to sleep and another process to wake it up. They have extremely good fast paths (avoiding kernel calls in those cases) which matters a lot if you use them as a mutex but not so much if you use them as a semaphore.

You would only need its two most primitive functions. One, FUTEX_WAIT, puts a kernel to sleep if, and only if, a particular entry in shared memory has a particular value. The other, FUTEX_WAKE, wakes a process that has gone to sleep with FUTEX_WAIT.

Your "wait" code would atomically check a shared variable to see that it needed to sleep and then call FUTEX_WAIT to go to sleep if, and only if, the shared variable has not changed. Your "wake" code would change the value of the atomic shared variable and then call FUTEX_WAKE to wake any thread that was sleeping.

The 32-bit/64-bit issue would not matter at all if you use a 64-bit shared variable but only put meaningful data in the first 32-bits so it would work the same whether addressed as a 64-bit variable or a 32-bit variable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM