func readImage(p string) { defer wg.Done() handler, err := os.Open(p) if err != nil { fmt.Println(err) runtime.Goexit() } var decoder imgDecoder switch strings.ToLower(filepath.Ext(p)) { case ".png": decoder = png.Decode case ".jpg": decoder = jpeg.Decode case ".gif": decoder = gif.Decode } img, err := decoder(handler) if err != nil { fmt.Println(err) runtime.Goexit() } imgBufferLock.Lock() myImages = append(myImages, myImage{ img: img, name: filepath.Base(p), }) imgBufferLock.Unlock() }
func main() { runtime.GOMAXPROCS(1) wg := new(sync.WaitGroup) wg.Add(1) go func() { for i := 0; i < 15; i++ { if i > 5 { runtime.Goexit() } fmt.Println(i) time.Sleep(time.Second * 1) } }() go func() { defer wg.Done() defer fmt.Println("A.defer") func() { defer fmt.Println("B.defer") runtime.Goexit() // 立即终止当前线程 fmt.Println("B") // 不会执行 }() fmt.Println("A") // 不会执行 }() wg.Wait() time.Sleep(time.Second * 10) fmt.Println("main") }
func main() { page_count := 1 download_count := 0 for { offset := page_count * 50 param := map[string]string{ "AppId": appid, "Version": "2.2", "Market": "ja-JP", "Sources": "Image", "Image.Count": strconv.Itoa(50), "Image.Offset": strconv.Itoa(offset), "Adult": "off", "Query": "おっぱい", } var sr *json_root res, err := http.Get(get_request_uri(param)) if err != nil { break } reader := bufio.NewReader(res.Body) line, err := reader.ReadBytes('\n') if err == nil { break } json.Unmarshal(line, &sr) for i := 0; i < len(sr.SearchResponse.Image.Results); i++ { result := sr.SearchResponse.Image.Results[i] if regexp.MustCompile(".jpg$").FindString(result.MediaUrl) == "" { continue } download_count++ filename := md5hex(encode_utf8(result.MediaUrl)) + ".jpg" filepath := dir + filename if _, err := os.Stat(filepath); err == nil { continue } fmt.Printf("%d : Download... %s\n", download_count, result.MediaUrl) res, err := http.Get(result.MediaUrl) if err != nil { runtime.Goexit() } data, err := ioutil.ReadAll(res.Body) if err != nil { runtime.Goexit() } if regexp.MustCompile("^image").FindString(http.DetectContentType(data)) != "" { ioutil.WriteFile(filepath, data, 0666) } } page_count++ } }
// findIdentifier looks for an identifier at byte-offset searchpos // inside the parsed source represented by node. // If it is part of a selector expression, it returns // that expression rather than the identifier itself. // // As a special case, if it finds an import // spec, it returns ImportSpec. // func findIdentifier(f *ast.File, searchpos int) ast.Node { ec := make(chan ast.Node) found := func(startPos, endPos token.Pos) bool { start := types.FileSet.Position(startPos).Offset end := start + int(endPos-startPos) return start <= searchpos && searchpos <= end } go func() { var visit func(ast.Node) bool visit = func(n ast.Node) bool { var startPos token.Pos switch n := n.(type) { default: return true case *ast.Ident: startPos = n.NamePos case *ast.SelectorExpr: startPos = n.Sel.NamePos case *ast.ImportSpec: startPos = n.Pos() case *ast.StructType: // If we find an anonymous bare field in a // struct type, its definition points to itself, // but we actually want to go elsewhere, // so assume (dubiously) that the expression // works globally and return a new node for it. for _, field := range n.Fields.List { if field.Names != nil { continue } t := field.Type if pt, ok := field.Type.(*ast.StarExpr); ok { t = pt.X } if id, ok := t.(*ast.Ident); ok { if found(id.NamePos, id.End()) { ec <- parseExpr(f.Scope, id.Name) runtime.Goexit() } } } return true } if found(startPos, n.End()) { ec <- n runtime.Goexit() } return true } ast.Walk(FVisitor(visit), f) ec <- nil }() ev := <-ec if ev == nil { fail("no identifier found") } return ev }
func GoexitInPanic() { go func() { defer func() { runtime.Goexit() }() panic("hello") }() runtime.Goexit() }
func RunFixFingers(c *types.Chord_t) { runtime.Goexit() //XXX XXX XXX var next = 0 for { if !c.Alive { runtime.Goexit() } c.FixFingers(&next, nil) time.Sleep(1200 * time.Millisecond) } }
// 每个连接在此函数中完成所有事情,不再启动多个协程 func handle_logic(clientConn *net.TCPConn) { defer func() { // 必须要先声明defer,否则不能捕获到panic异常 if err := recover(); err != nil { jlog.Critical("!!!!!!!!!!!!! LOGIC FANIC error: ", err) //fmt.Println("!!!!!!!!!!!!! LOGIC FANIC error: ", err) clientConn.Close() runtime.Goexit() } }() tcpBuffer := make([]byte, nfconst.LEN_TCP_BUFFER) clientConn.SetReadBuffer(nfconst.LEN_TCP_BUFFER) var handle *nfnet.OrgStreamHandler = nfnet.NewOrgStreamHandler() nullmsg := make([]byte, 0) var msg []byte for { n, err := clientConn.Read(tcpBuffer[0:]) if err != nil { if err.Error() == "EOF" { // 跳出循环, 并处理已经接收到的数据 jlog.Infof("%s close, tcp read end, break read loop", clientConn.RemoteAddr().String()) } else { jlog.Errorf("%s tcp read error %s, break read loop", clientConn.RemoteAddr().String(), err.Error()) } //jlog.Tracef("---------- D_%s, read err: %s", clientConn.RemoteAddr().String(), err.Error()) clientConn.Close() jlog.Infof("==================== goroutine exit\n") runtime.Goexit() break } done, buf, err1 := handle.AddStream(tcpBuffer[0:n]) msg = buf if err1 != nil { jlog.Error("data add stream error, ", err1.Error()) } else if done { // 处理消息 msgHandler(clientConn, msg) msg = nullmsg } } // 如果执行到了这里, 那么就是 read的时候发生错误到了此处 // 一个完整的包具备的最小长度为 头2字节,cmd 1字节, 负载长度2字节,校验1字节,尾2字节 = 8字节 /* n_msg := len(msg) if n_msg >= nfconst.LEN_MIN_PACKAGE && msg[0] == nfconst.SOCK_PACK_HEADER_L && msg[1] == nfconst.SOCK_PACK_HEADER_H && msg[n_msg-2] == nfconst.SOCK_PACK_ENDER_L && msg[n_msg-1] == nfconst.SOCK_PACK_ENDER_H { msgHandler(clientConn, msg) } */ }
// Main workhorse method // Handles any incoming packet func handleRequest(conn *net.UDPConn, localAddr string, remoteAddr string, secret string, message []byte, clientAddr *net.UDPAddr) { // Returns true if message is a valid HashMessage check, hashMessage := parseHashMessage(message) if check { // Check that client has been given a nonce hash := getClientHash(clientAddr, clientList) if len(hash) <= 0 { // Create and Send Error Message var packet []byte = createErrorMessage("unknown remote client address") conn.WriteToUDP(packet, clientAddr) runtime.Goexit() } // Check that hash from packet matches one we expected var match bool = checkHashMatch(hash, hashMessage.Hash) if !match { // Create and Send Error Message var packet []byte = createErrorMessage("unexpected hash value") conn.WriteToUDP(packet, clientAddr) runtime.Goexit() } // get Fortune Server Info client, _ := rpc.Dial("tcp", remoteAddr) fortuneInfo := FortuneInfoMessage{} err := client.Call("FortuneServerRPC.GetFortuneInfo", clientAddr.String(), &fortuneInfo) errorCheck(err, "rcp call") // send FortuneInfoMessage var packet []byte = createFortuneInfoMessage(fortuneInfo) conn.WriteToUDP(packet, clientAddr) } else { // Send a new Nonce to the client var nonce int64 = generateNonce() hash := computeMd5(secret, nonce) recordClientHash(clientAddr, hash, clientList) var packet = createNonceMessage(nonce) conn.WriteToUDP(packet, clientAddr) } }
func main() { var urls = flag.String("s", nats.DefaultURL, "The nats server URLs (separated by comma)") var showTime = flag.Bool("t", false, "Display timestamps") log.SetFlags(0) flag.Usage = usage flag.Parse() args := flag.Args() if len(args) < 2 { usage() } nc, err := nats.Connect(*urls) if err != nil { log.Fatalf("Can't connect: %v\n", err) } subj, reply, i := args[0], args[1], 0 nc.Subscribe(subj, func(msg *nats.Msg) { i++ printMsg(msg, i) nc.Publish(msg.Reply, []byte(reply)) }) log.Printf("Listening on [%s]\n", subj) if *showTime { log.SetFlags(log.LstdFlags) } runtime.Goexit() }
// Abort aborts the thread's current computation, // causing the innermost Try to return err. func (t *Thread) Abort(err os.Error) { if t.abort == nil { panicln("abort:", err.String()) } t.abort <- err runtime.Goexit() }
func runApp(cmd *Command, args []string) { exit := make(chan bool) if len(args) != 1 { colorLog("[ERRO] Cannot start running[ %s ]\n", "argument 'appname' is missing") os.Exit(2) } crupath, _ := os.Getwd() Debugf("current path:%s\n", crupath) err := loadConfig() if err != nil { colorLog("[ERRO] Fail to parse bee.json[ %s ]", err) } var paths []string paths = append(paths, path.Join(crupath, conf.DirStruct.Controllers), path.Join(crupath, conf.DirStruct.Models), path.Join(crupath, "./")) // Current path. // Because monitor files has some issues, we watch current directory // and ignore non-go files. paths = append(paths, conf.DirStruct.Others...) paths = append(paths, conf.MainFiles.Others...) NewWatcher(paths) appname = args[0] Autobuild() for { select { case <-exit: runtime.Goexit() } } }
func (self *Pool) Put(element interface{}, timeoutMs time.Duration) bool { // logger.Infof("Putting! (Size: %v, Cap: %v)", len(self.container), cap(self.container)) if self.Closed() { return false } result := false if timeoutMs > 0 { sign := make(chan bool) go func() { time.AfterFunc(5*time.Millisecond, func() { if !result { logger.Infof("Putting Timeout! (Size: %v, Cap: %v, Element: %v)", len(self.container), cap(self.container), element) sign <- result } runtime.Goexit() }) self.container <- element result = true sign <- result }() return <-sign } else { if len(self.container) >= self.Size { result = false } else { self.container <- element result = true } } return result }
func (m *MockLogger) Skip(args ...interface{}) { m.skipped = true if m.funcSkip != nil { m.funcSkip(args...) } runtime.Goexit() }
func readOb(s net.Conn, buf []byte) { x, err := io.ReadFull(s, buf) if err != nil || x != len(buf) { log.Printf("Error reading part: %s", err) runtime.Goexit() } }
func main() { m := Message{Name: "Alice", Body: "Hello"} m.startLoopTimer() fmt.Println("starting ....") runtime.Goexit() os.Exit(0) m = Message{Name: "Alice", Body: "Hello"} b, _ := json.Marshal(m) var d Message json.Unmarshal(b, &d) fmt.Printf("%s, %s, %d\n", d.Name, d.Body, d.Time) l := testjson{ab: true, bb: 1, cb: "abcd", db: 3} e, _ := json.Marshal(l) var n testjson json.Unmarshal(e, &n) fmt.Printf("%t, %d, %s\n", n.ab, n.bb, n.cb) os.Exit(0) gWG.Add(1) go loop() gWG.Add(1) go loop() gWG.Wait() }
// findIdentifier looks for an identifier at byte-offset searchpos // inside the parsed source represented by node. // If it is part of a selector expression, it returns // that expression rather than the identifier itself. // // As a special case, if it finds an import // spec, it returns ImportSpec. // func findIdentifier(f *ast.File, searchpos int) ast.Node { ec := make(chan ast.Node) go func() { visit := func(n ast.Node) bool { var startPos token.Pos switch n := n.(type) { case *ast.Ident: startPos = n.NamePos case *ast.SelectorExpr: startPos = n.Sel.NamePos case *ast.ImportSpec: startPos = n.Pos() default: return true } start := types.FileSet.Position(startPos).Offset end := start + int(n.End()-startPos) if start <= searchpos && searchpos <= end { ec <- n runtime.Goexit() } return true } ast.Walk(FVisitor(visit), f) ec <- nil }() ev := <-ec if ev == nil { fail("no identifier found") } return ev }
func (cd *CmpData) handle(msg Msg) { // Call the appropriate function based on the msg type switch m := msg.(type) { case MsgTick: // Check at the start of the tick because Game actually removes at // the end of the previous tick if _, ok := cd.states[cmpId.Remove]; ok { Send(cd, m.Origin, MsgTick{cd.input}) runtime.Goexit() // Entity was removed, bail } cd.update(cd.svc) Send(cd, m.Origin, MsgTick{cd.input}) // Reply that we are updated case MsgGetState: cd.sendState(m) case MsgGetAllStates: cd.sendAllStates(m) case MsgSetState: cd.SetState(m.State) case MsgAddAction: cd.AddAction(m.Action) case MsgRunAction: m.Action.Act(cd, cd.svc) if m.Add { cd.AddAction(m.Action) } } }
func main() { flag.Parse() conn, err := common.Connect() if err != nil { panic(err) } uplink = conn conn.Subscribe(uplink.ID+":input", func(subj, unusedReply string, msg *common.Message) { if msg.Kind != "TextMessage" { return } if !strings.HasPrefix(msg.Body, ";source") { return } reply := &common.Message{ Destination: msg.ReplyTo, Kind: "TextMessage", Body: "Source code: https://github.com/Xe/betterbot", } conn.Publish(msg.Via+":input", reply) }) conn.Publish("betterbot.birth", &common.Birth{ ID: uplink.ID, EventKinds: []string{"TextMessage"}, }) runtime.Goexit() }
func handleRequest(sock net.Conn, backend chan Request) (rv bool) { var req Request // parse request message if err := req.ReadFrom(bufio.NewReader(sock)); err != nil { log.Printf("failed to read request: %s", err) runtime.Goexit() } log.Printf("processing request %s", req) // send newly-formed request message to server for processing req.Reply = make(chan Response, 1) backend <- req // get response from server and dispatch it or die if fatal error // occurred resp := <-req.Reply rv = !resp.Fatal if rv { log.Printf("got response %s", resp) if err := resp.WriteTo(bufio.NewWriter(sock)); err != nil { log.Printf("error writing response: %s", err) return true } } else { log.Printf("error during processing on %s; hanging up", sock) } return }
func (e *env) Run(args ...string) (out, err []byte, exitCode int) { outbuf := new(bytes.Buffer) errbuf := new(bytes.Buffer) os.Args = append(os.Args[:1], args...) cmdmain.Stdout, cmdmain.Stderr = outbuf, errbuf if e.stdin == nil { cmdmain.Stdin = strings.NewReader("") } else { cmdmain.Stdin = e.stdin } exitc := make(chan int, 1) cmdmain.Exit = func(code int) { exitc <- code runtime.Goexit() } go func() { cmdmain.Main() cmdmain.Exit(0) }() select { case exitCode = <-exitc: case <-time.After(e.timeout()): panic("timeout running command") } out = outbuf.Bytes() err = errbuf.Bytes() return }
func (state *InputPeerState) Cmp(result string, left string, right string, q chan int) chan bool { done := make(chan bool, 1) //Buffer to avoid hangs go func() { requestID := atomic.AddInt64(&state.RequestID, 1) status := make(chan *sproto.Response, INITIAL_CHANNEL_SIZE) state.SetChannelForRequest(requestID, status) action := &sproto.Action{} t := sproto.Action_Cmp action.Action = &t action.Result = &result action.RequestCode = &requestID action.Share0 = &left action.Share1 = &right state.PubNaggleChannel <- action received := 0 for received < len(state.ComputeSlaves) { <-status received += 1 //fmt.Println("Returned cmp return") } state.DelChannelForRequest(requestID) done <- true runtime.Goexit() }() return done }
func (m *MockLogger) Fatalf(format string, args ...interface{}) { m.failed = true if m.funcFatalf != nil { m.funcFatalf(format, args...) } runtime.Goexit() }
func main() { runtime.GOMAXPROCS(runtime.NumCPU()) go func() { result = make(chan int) defer close(result) sum := 0 println("This is child process !!!") for i := 0; i < 1000; i++ { sum += i } // time.Sleep(2 * time.Second) result <- sum }() //time.Sleep(2 * time.Second) // println("This is parent process !!!") for { time.Sleep(time.Second) if r, ok := <-result; ok == true { fmt.Printf("The result is %d\n", r) break } else { println("Not ready") } } runtime.Goexit() }
func (m *MockLogger) Fatal(args ...interface{}) { m.failed = true if m.funcFatal != nil { m.funcFatal(args...) } runtime.Goexit() }
// FailNow marks the function as having failed and stops its execution. // Execution will continue at the next test or benchmark. // FailNow must be called from the goroutine running the // test or benchmark function, not from other goroutines // created during the test. Calling FailNow does not stop // those other goroutines. func (c *common) FailNow() { c.Fail() // Calling runtime.Goexit will exit the goroutine, which // will run the deferred functions in this goroutine, // which will eventually run the deferred lines in tRunner, // which will signal to the test loop that this test is done. // // A previous version of this code said: // // c.duration = ... // c.signal <- c.self // runtime.Goexit() // // This previous version duplicated code (those lines are in // tRunner no matter what), but worse the goroutine teardown // implicit in runtime.Goexit was not guaranteed to complete // before the test exited. If a test deferred an important cleanup // function (like removing temporary files), there was no guarantee // it would run on a test failure. Because we send on c.signal during // a top-of-stack deferred function now, we know that the send // only happens after any other stacked defers have completed. c.finished = true runtime.Goexit() }
func (m *MockLogger) Skipf(format string, args ...interface{}) { m.skipped = true if m.funcSkipf != nil { m.funcSkipf(format, args...) } runtime.Goexit() }
// Member looks for a member with the given name inside // the type. For packages, the member can be any exported // top level declaration inside the package. func (t Type) Member(name string, importer Importer) *ast.Object { debugp("member %v '%s' {", t, name) if t.Pkg != "" && !ast.IsExported(name) { return nil } c := make(chan *ast.Object) go func() { if !Panic { defer func() { if err := recover(); err != nil { log.Printf("panic: %v", err) c <- nil } }() } doMembers(t, name, importer, func(obj *ast.Object) { if obj.Name == name { c <- obj runtime.Goexit() } }) c <- nil }() m := <-c debugp("} -> %v", m) return m }
func (c *CMD) Do() ([]byte, error) { if c.debug { fmt.Printf("[cmd] %s\n", c.raw) } if len(c.raw) <= 0 { return nil, fmt.Errorf("raw cmd is nil") } var err error if c.Execution != nil { var bs []byte sh := make(chan bool) go func() { go func() { <-time.After(8e9) runtime.Goexit() }() bs, err = c.Execution(c.cmd, c.args...) sh <- true }() select { case <-sh: Checkerr(err) if c.debug { fmt.Println(*(*string)(unsafe.Pointer(&bs))) } return bs, err case <-time.After(8e9): err = fmt.Errorf("Timeout") } } return nil, err }
// Abort aborts the thread's current computation, // causing the innermost Try to return err. func (t *Thread) Abort(err error) { if t.abort == nil { panic("abort: " + err.Error()) } t.abort <- err runtime.Goexit() }
func read_tcp_conn(tcpConn *net.TCPConn, connChan chan []byte) { buffer := make([]byte, 2048) tcpConn.SetReadBuffer(2048) for { n, err := tcpConn.Read(buffer[0:]) if err != nil { log.Println("one tcp connection read function failed!") log.Println("one tcp connection close now!") tcpConn.Close() runtime.Goexit() } else { connChan <- buffer[0 : n-1] } } }