golangでselectタイムアウトメカニズムを実現
6362 ワード
c/c++開発では、osと最も適切なapiが使用できます.例えば、タイムアウトメカニズム付き反発ロックなどです.
タイムアウトメカニズム付きepoll
など.
しかしgolangのような新しい言語にとって、完璧なところはまだいくつかあります.例えば、一部のオープンソースコンポーネントの書き換え、cordis、mysqlなどはgolangで書き換え、一部のapiは確かにそれほど完備していない.
多重化の場合、信号をずっと待つことはできない.万一信号で死んだら、いつも馬鹿に待っているのではないでしょうか.タイムアウトメカニズムがありますgolangは,元のapiでは条件を満たすことはできないが,組み合わせてアプリケーション層でこの機能を実現することができる.(これもlinuxマイクロカーネルの設計思想に合っています)
#include
#include
int pthread_mutex_timedlock(pthread_mutex_t *restrict mutex,
const struct timespec *restrict abstime);
タイムアウトメカニズム付きepoll
#include
int epoll_wait(int epfd, struct epoll_event *events,
int maxevents, int timeout);
int epoll_pwait(int epfd, struct epoll_event *events,
int maxevents, int timeout,
const sigset_t *sigmask);
など.
しかしgolangのような新しい言語にとって、完璧なところはまだいくつかあります.例えば、一部のオープンソースコンポーネントの書き換え、cordis、mysqlなどはgolangで書き換え、一部のapiは確かにそれほど完備していない.
多重化の場合、信号をずっと待つことはできない.万一信号で死んだら、いつも馬鹿に待っているのではないでしょうか.タイムアウトメカニズムがありますgolangは,元のapiでは条件を満たすことはできないが,組み合わせてアプリケーション層でこの機能を実現することができる.(これもlinuxマイクロカーネルの設計思想に合っています)
package main
import (
"fmt"
"time"
"strconv"
)
func main() {
ch := make(chan string)
quit := make(chan bool)
go func() {
for i := 0; i < 10; i++ {
ch strconv.Itoa(i)
time.Sleep(time.Second)
}
}()
go func() {
timeout := time.After(time.Second * 2) // , select
flagrun := true
for ; flagrun == true ; {
select {
case timeout:
fmt.Println("2 second timout,then send one message to channel quit ,and exit for loop and goroutine")
flagrun = false
quit true
case str := ch:
fmt.Println("string: ", str)
}
}
}()
quit
close(ch)
close(quit)
fmt.Println("endof process")
}