最高效的进(线)程间通信机制--eventfd
我們常用的進(jìn)程(線程)間通信機(jī)制有管道,信號,消息隊(duì)列,信號量,共享內(nèi)存,socket等等,其中主要作為進(jìn)程(線程)間通知/等待的有管道pipe和socketpair。線程還有特別的condition。
今天來看一個liunx較新的系統(tǒng)調(diào)用,它是從LINUX 2.6.27版本開始增加的,主要用于進(jìn)程或者線程間的通信(如通知/等待機(jī)制的實(shí)現(xiàn))。
首先來看一下函數(shù)原型:
[cpp]?view plain?copy下面是它man手冊中的描述,我照著翻譯了一遍(我英語四級434,你們要是懷疑下文的話,可以直接去man eventfd ^^):
eventfd()創(chuàng)建了一個"eventfd object",能在用戶態(tài)用做事件wait/notify機(jī)制,通過內(nèi)核取喚醒用戶態(tài)的事件。這個對象保存了一個內(nèi)核維護(hù)的uint64_t類型的整型counter。這個counter初始值被參數(shù)initval指定,一般初值設(shè)置為0。
它的標(biāo)記可以有以下屬性:
EFD_CLOECEX,EFD_NONBLOCK,EFD_SEMAPHORE。
在linux直到版本2.6.26,這個flags參數(shù)是沒用的,必須指定為0。
它返回了一個引用eventfd object的描述符。這個描述符可以支持以下操作:
read:如果計(jì)數(shù)值counter的值不為0,讀取成功,獲得到該值。如果counter的值為0,非阻塞模式,會直接返回失敗,并把errno的值指紋EINVAL。如果為阻塞模式,一直會阻塞到counter為非0位置。
write:會增加8字節(jié)的整數(shù)在計(jì)數(shù)器counter上,如果counter的值達(dá)到0xfffffffffffffffe時,就會阻塞。直到counter的值被read。阻塞和非阻塞情況同上面read一樣。
close:這個操作不用說了。
重點(diǎn)是支持這個:
?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).
它的內(nèi)核代碼實(shí)現(xiàn)是這樣子的:
[cpp]?view plain?copy本質(zhì)就是做了一次喚醒,不用read,也不用write,與eventfd_write的區(qū)別是不用阻塞。
說了這么多,我們來看一個例子,理解理解其中的含義:
[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)保證子進(jìn)程循環(huán)寫入完畢,得到的值就是綜合28。如果不用sleep(2)來保證時序,當(dāng)子進(jìn)程寫入一個值,父進(jìn)程會立馬從eventfd讀出該值。
總結(jié)
以上是生活随笔為你收集整理的最高效的进(线)程间通信机制--eventfd的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 成都欢乐谷预约怎么预约
- 下一篇: 比特币源码学习笔记(一)