当前位置: 首页>>代码示例>>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;未经允许,请勿转载。