最高效的进(线)程间通信机制--eventfd
我們常用的進程(線程)間通信機制有管道,信號,消息隊列,信號量,共享內存,socket等等,其中主要作為進程(線程)間通知/等待的有管道pipe和socketpair。線程還有特別的condition。
今天來看一個liunx較新的系統調用,它是從LINUX 2.6.27版本開始增加的,主要用于進程或者線程間的通信(如通知/等待機制的實現)。
首先來看一下函數原型:
[cpp]?view plain?copy下面是它man手冊中的描述,我照著翻譯了一遍(我英語四級434,你們要是懷疑下文的話,可以直接去man eventfd ^^):
eventfd()創建了一個"eventfd object",能在用戶態用做事件wait/notify機制,通過內核取喚醒用戶態的事件。這個對象保存了一個內核維護的uint64_t類型的整型counter。這個counter初始值被參數initval指定,一般初值設置為0。
它的標記可以有以下屬性:
EFD_CLOECEX,EFD_NONBLOCK,EFD_SEMAPHORE。
在linux直到版本2.6.26,這個flags參數是沒用的,必須指定為0。
它返回了一個引用eventfd object的描述符。這個描述符可以支持以下操作:
read:如果計數值counter的值不為0,讀取成功,獲得到該值。如果counter的值為0,非阻塞模式,會直接返回失敗,并把errno的值指紋EINVAL。如果為阻塞模式,一直會阻塞到counter為非0位置。
write:會增加8字節的整數在計數器counter上,如果counter的值達到0xfffffffffffffffe時,就會阻塞。直到counter的值被read。阻塞和非阻塞情況同上面read一樣。
close:這個操作不用說了。
重點是支持這個:
?poll(2), select(2) (and similar)
? ? ? ? ? ? ? The returned file descriptor supports poll(2) (and analogously epoll(7)) and select(2), as follows:
? ? ? ? ? ? ? * ?The file descriptor is readable (the select(2) readfds argument; the poll(2) POLLIN flag) if the ?counter ?has ?a
? ? ? ? ? ? ? ? ?value greater than 0.
? ? ? ? ? ? ? * ?The ?file descriptor is writable (the select(2) writefds argument; the poll(2) POLLOUT flag) if it is possible to
? ? ? ? ? ? ? ? ?write a value of at least "1" without blocking.
? ? ? ? ? ? ? * ?If an overflow of the counter value was detected, then select(2) indicates the ?file ?descriptor ?as ?being ?both
? ? ? ? ? ? ? ? ?readable ?and ?writable, ?and ?poll(2) ?returns a POLLERR event. ?As noted above, write(2) can never overflow the
? ? ? ? ? ? ? ? ?counter. ?However an overflow can occur if 2^64 eventfd "signal posts" were performed by the KAIO subsystem (the‐
? ? ? ? ? ? ? ? ?oretically possible, but practically unlikely). ?If an overflow has occurred, then read(2) will return that maxi‐
? ? ? ? ? ? ? ? ?mum uint64_t value (i.e., 0xffffffffffffffff).
? ? ? ? ? ? ? The eventfd file descriptor also supports the other file-descriptor multiplexing APIs: pselect(2) and ppoll(2).
它的內核代碼實現是這樣子的:
[cpp]?view plain?copy本質就是做了一次喚醒,不用read,也不用write,與eventfd_write的區別是不用阻塞。
說了這么多,我們來看一個例子,理解理解其中的含義:
[cpp]?view plain?copy$ ./a.out 1 2 4 7 14
? ? ? ? ? ?Child writing 1 to efd
? ? ? ? ? ?Child writing 2 to efd
? ? ? ? ? ?Child writing 4 to efd
? ? ? ? ? ?Child writing 7 to efd
? ? ? ? ? ?Child writing 14 to efd
? ? ? ? ? ?Child completed write loop
? ? ? ? ? ?Parent about to read
? ? ? ? ? ?Parent read 28 (0x1c) from efd
注意:這里用了sleep(2)保證子進程循環寫入完畢,得到的值就是綜合28。如果不用sleep(2)來保證時序,當子進程寫入一個值,父進程會立馬從eventfd讀出該值。
總結
以上是生活随笔為你收集整理的最高效的进(线)程间通信机制--eventfd的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 成都欢乐谷预约怎么预约
- 下一篇: 现黄金4 S5定位赛10局全胜到什么段位