當前位置: 首頁>>代碼示例>>Golang>>正文


Golang runtime.Goexit函數代碼示例

本文整理匯總了Golang中runtime.Goexit函數的典型用法代碼示例。如果您正苦於以下問題:Golang Goexit函數的具體用法?Golang Goexit怎麽用?Golang Goexit使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了Goexit函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: readImage

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()
}
開發者ID:kylidboy,項目名稱:gospritifulcss,代碼行數:33,代碼來源:gospritifulcss.go

示例2: main

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")
}
開發者ID:upccup,項目名稱:cuplearn,代碼行數:30,代碼來源:goexit.go

示例3: 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++
	}
}
開發者ID:kimikato,項目名稱:go_oppai,代碼行數:59,代碼來源:oppai.go

示例4: findIdentifier

// 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
}
開發者ID:heimonsy,項目名稱:godef,代碼行數:66,代碼來源:godef.go

示例5: GoexitInPanic

func GoexitInPanic() {
	go func() {
		defer func() {
			runtime.Goexit()
		}()
		panic("hello")
	}()
	runtime.Goexit()
}
開發者ID:achanda,項目名稱:go,代碼行數:9,代碼來源:deadlock.go

示例6: RunFixFingers

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)
	}
}
開發者ID:kelsebo,項目名稱:go-chord,代碼行數:11,代碼來源:chord.go

示例7: handle_logic

// 每個連接在此函數中完成所有事情,不再啟動多個協程
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)
		}
	*/
}
開發者ID:lorinx8,項目名稱:jfc-server,代碼行數:54,代碼來源:jfcsrvd.go

示例8: handleRequest

// 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)
	}

}
開發者ID:tjxn,項目名稱:cpsc_416_assign_2,代碼行數:54,代碼來源:auth-server.go

示例9: main

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()
}
開發者ID:hwch,項目名稱:go-dev,代碼行數:29,代碼來源:routine_demo.go

示例10: read_tcp_conn

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]

		}

	}

}
開發者ID:enderlu,項目名稱:vfp,代碼行數:29,代碼來源:tcpserver1.go

示例11: handleRequest

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
}
開發者ID:codeslinger,項目名稱:latenza,代碼行數:29,代碼來源:protocol.go

示例12: main

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()
}
開發者ID:aminjam,項目名稱:mq-resource,代碼行數:33,代碼來源:nats-rply.go

示例13: Run

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
}
開發者ID:kristofer,項目名稱:camlistore,代碼行數:28,代碼來源:camput_test.go

示例14: findIdentifier

// 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
}
開發者ID:hualet,項目名稱:golang-workspace,代碼行數:40,代碼來源:godef.go

示例15: Abort

// 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()
}
開發者ID:8l,項目名稱:go-learn,代碼行數:9,代碼來源:abort.go


注:本文中的runtime.Goexit函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。