• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang context.WithCancel函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中context.WithCancel函数的典型用法代码示例。如果您正苦于以下问题:Golang WithCancel函数的具体用法?Golang WithCancel怎么用?Golang WithCancel使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了WithCancel函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: ExampleContextRelationShip

func ExampleContextRelationShip() {
	ctx1, cancel1 := context.WithCancel(context.Background())
	ctx2, cancel2 := context.WithCancel(ctx1)
	var wg sync.WaitGroup

	wg.Add(2)
	go func() {
		defer wg.Done()
		log.Printf("waiting for ctx1...")
		<-ctx1.Done()
		log.Printf("ctx1.Done() returns")
	}()

	go func() {
		defer wg.Done()
		log.Printf("waiting for ctx2....")
		<-ctx2.Done()
		log.Printf("ctx2.Done() returns")
	}()

	time.AfterFunc(time.Second*5, cancel2)
	time.AfterFunc(time.Second*1, cancel1) //触发 1 2 同时结束

	wg.Wait()
}
开发者ID:oywc410,项目名称:MYPG,代码行数:25,代码来源:04.go


示例2: TestDoubleGet

func TestDoubleGet(t *testing.T) {
	net := tn.VirtualNetwork(mockrouting.NewServer(), delay.Fixed(kNetworkDelay))
	sg := NewTestSessionGenerator(net)
	defer sg.Close()
	bg := blocksutil.NewBlockGenerator()

	t.Log("Test a one node trying to get one block from another")

	instances := sg.Instances(2)
	blocks := bg.Blocks(1)

	ctx1, cancel1 := context.WithCancel(context.Background())
	blkch1, err := instances[1].Exchange.GetBlocks(ctx1, []*cid.Cid{blocks[0].Cid()})
	if err != nil {
		t.Fatal(err)
	}

	ctx2, cancel2 := context.WithCancel(context.Background())
	defer cancel2()

	blkch2, err := instances[1].Exchange.GetBlocks(ctx2, []*cid.Cid{blocks[0].Cid()})
	if err != nil {
		t.Fatal(err)
	}

	// ensure both requests make it into the wantlist at the same time
	time.Sleep(time.Millisecond * 100)
	cancel1()

	_, ok := <-blkch1
	if ok {
		t.Fatal("expected channel to be closed")
	}

	err = instances[0].Exchange.HasBlock(blocks[0])
	if err != nil {
		t.Fatal(err)
	}

	select {
	case blk, ok := <-blkch2:
		if !ok {
			t.Fatal("expected to get the block here")
		}
		t.Log(blk)
	case <-time.After(time.Second * 5):
		t.Fatal("timed out waiting on block")
	}

	for _, inst := range instances {
		err := inst.Exchange.Close()
		if err != nil {
			t.Fatal(err)
		}
	}
}
开发者ID:VictorBjelkholm,项目名称:go-ipfs,代码行数:56,代码来源:bitswap_test.go


示例3: NewPool

// NewPool creates a Pool
func NewPool(parentCtx context.Context) *Pool {
	baseCtx, baseCancel := context.WithCancel(parentCtx)
	ctx, cancel := context.WithCancel(baseCtx)
	return &Pool{
		baseCtx:    baseCtx,
		baseCancel: baseCancel,
		ctx:        ctx,
		cancel:     cancel,
	}
}
开发者ID:vdemeester,项目名称:traefik,代码行数:11,代码来源:routine.go


示例4: InitializeKeyspace

// InitializeKeyspace sets the ipns record for the given key to
// point to an empty directory.
func InitializeKeyspace(n *core.IpfsNode, key ci.PrivKey) error {
	emptyDir := ft.EmptyDirNode()
	nodek, err := n.DAG.Add(emptyDir)
	if err != nil {
		return err
	}

	ctx, cancel := context.WithCancel(n.Context())
	defer cancel()

	err = n.Pinning.Pin(ctx, emptyDir, false)
	if err != nil {
		return err
	}

	err = n.Pinning.Flush()
	if err != nil {
		return err
	}

	pub := nsys.NewRoutingPublisher(n.Routing, n.Repo.Datastore())
	if err := pub.Publish(ctx, key, path.FromCid(nodek)); err != nil {
		return err
	}

	return nil
}
开发者ID:qnib,项目名称:go-ipfs,代码行数:29,代码来源:common.go


示例5: republishEntries

func (rp *Republisher) republishEntries(p goprocess.Process) error {
	ctx, cancel := context.WithCancel(gpctx.OnClosingContext(p))
	defer cancel()

	for id, _ := range rp.entries {
		log.Debugf("republishing ipns entry for %s", id)
		priv := rp.ps.PrivKey(id)

		// Look for it locally only
		_, ipnskey := namesys.IpnsKeysForID(id)
		p, seq, err := rp.getLastVal(ipnskey)
		if err != nil {
			if err == errNoEntry {
				continue
			}
			return err
		}

		// update record with same sequence number
		eol := time.Now().Add(rp.RecordLifetime)
		err = namesys.PutRecordToRouting(ctx, priv, p, seq, eol, rp.r, id)
		if err != nil {
			return err
		}
	}

	return nil
}
开发者ID:tswindell,项目名称:go-ipfs,代码行数:28,代码来源:repub.go


示例6: TestDoesNotDeadLockIfContextCancelledBeforePublish

func TestDoesNotDeadLockIfContextCancelledBeforePublish(t *testing.T) {

	g := blocksutil.NewBlockGenerator()
	ctx, cancel := context.WithCancel(context.Background())
	n := New()
	defer n.Shutdown()

	t.Log("generate a large number of blocks. exceed default buffer")
	bs := g.Blocks(1000)
	ks := func() []*cid.Cid {
		var keys []*cid.Cid
		for _, b := range bs {
			keys = append(keys, b.Cid())
		}
		return keys
	}()

	_ = n.Subscribe(ctx, ks...) // ignore received channel

	t.Log("cancel context before any blocks published")
	cancel()
	for _, b := range bs {
		n.Publish(b)
	}

	t.Log("publishing the large number of blocks to the ignored channel must not deadlock")
}
开发者ID:qnib,项目名称:go-ipfs,代码行数:27,代码来源:notifications_test.go


示例7: GoWithContext

// GoWithContext is similar to Go, but uses ctx as the parent of
// the context that will be used for the task's cancelation.
func GoWithContext(ctx context.Context, fnStart StartFuncCtx) *Single {
	ctx, cancel := context.WithCancel(ctx)
	fnS := func() error {
		return fnStart(ctx)
	}
	return goNoCtx(fnS, cancel)
}
开发者ID:npat-efault,项目名称:gohacks,代码行数:9,代码来源:task.go


示例8: TestDirBuilder

func TestDirBuilder(t *testing.T) {
	dserv := testu.GetDAGServ()
	ctx, closer := context.WithCancel(context.Background())
	defer closer()
	inbuf, node := testu.GetRandomNode(t, dserv, 1024)
	key := node.Cid()

	b := NewDirectory(dserv)

	b.AddChild(ctx, "random", key)

	dir := b.GetNode()
	outn, err := dir.GetLinkedProtoNode(ctx, dserv, "random")
	if err != nil {
		t.Fatal(err)
	}

	reader, err := NewDagReader(ctx, outn, dserv)
	if err != nil {
		t.Fatal(err)
	}

	outbuf, err := ioutil.ReadAll(reader)
	if err != nil {
		t.Fatal(err)
	}

	err = testu.ArrComp(inbuf, outbuf)
	if err != nil {
		t.Fatal(err)
	}

}
开发者ID:qnib,项目名称:go-ipfs,代码行数:33,代码来源:dirbuilder_test.go


示例9: TestEndSeek

func TestEndSeek(t *testing.T) {
	dserv := testu.GetDAGServ()

	n := testu.GetEmptyNode(t, dserv)
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	dagmod, err := NewDagModifier(ctx, n, dserv, testu.SizeSplitterGen(512))
	if err != nil {
		t.Fatal(err)
	}

	_, err = dagmod.Write(make([]byte, 100))
	if err != nil {
		t.Fatal(err)
	}

	offset, err := dagmod.Seek(0, os.SEEK_CUR)
	if offset != 100 {
		t.Fatal("expected the relative seek 0 to return current location")
	}

	offset, err = dagmod.Seek(0, os.SEEK_SET)
	if offset != 0 {
		t.Fatal("expected the absolute seek to set offset at 0")
	}

	offset, err = dagmod.Seek(0, os.SEEK_END)
	if offset != 100 {
		t.Fatal("expected the end seek to set offset at end")
	}
}
开发者ID:VictorBjelkholm,项目名称:go-ipfs,代码行数:32,代码来源:dagmodifier_test.go


示例10: TestRelativeSeek

func TestRelativeSeek(t *testing.T) {
	dserv := testu.GetDAGServ()
	n := testu.GetEmptyNode(t, dserv)
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	dagmod, err := NewDagModifier(ctx, n, dserv, testu.SizeSplitterGen(512))
	if err != nil {
		t.Fatal(err)
	}

	for i := 0; i < 64; i++ {
		dagmod.Write([]byte{byte(i)})
		if _, err := dagmod.Seek(1, os.SEEK_CUR); err != nil {
			t.Fatal(err)
		}
	}

	out, err := ioutil.ReadAll(dagmod)
	if err != nil {
		t.Fatal(err)
	}

	for i, v := range out {
		if v != 0 && i/2 != int(v) {
			t.Errorf("expected %d, at index %d, got %d", i/2, i, v)
		}
	}
}
开发者ID:VictorBjelkholm,项目名称:go-ipfs,代码行数:29,代码来源:dagmodifier_test.go


示例11: main

func main() {
	var rcpAddr, port string
	flag.StringVar(&rcpAddr, "rcp", ":3323", "rcp addr (default: ':3323')")
	flag.StringVar(&port, "http", ":3343", "http port (default: '3343')")
	flag.Parse()

	//START2 OMIT
	ctx := context.Background()
	ctx, cancel := context.WithCancel(ctx)
	defer cancel()

	m := runtime.NewServeMux()
	opts := []grpc.DialOption{grpc.WithInsecure()}
	err := idl.RegisterUserServiceHandlerFromEndpoint(ctx, m, rcpAddr, opts)
	if err != nil {
		fmt.Fprintf(os.Stderr, "cannot register service handler: %v\n", err)
		os.Exit(1)
	}

	// custom routes first, and cors handling on all requests
	h := cors(preMuxRouter(m))

	if err = http.ListenAndServe(port, h); err != nil {
		fmt.Fprintf(os.Stderr, "http server error: %v\n", err)
		os.Exit(1)
	}
	//END2 OMIT
}
开发者ID:euggo,项目名称:meetup,代码行数:28,代码来源:main.go


示例12: _

func _() {
	ctx, cancel := context.WithCancel() // ERROR "not used on all paths"
	if condition {
		cancel()
	}
	return // ERROR "this return statement may be reached without using the cancel var"
}
开发者ID:cdb-dev,项目名称:go,代码行数:7,代码来源:lostcancel.go


示例13: SetupInterruptHandler

func (i *cmdInvocation) SetupInterruptHandler(ctx context.Context) (io.Closer, context.Context) {

	intrh := NewIntrHandler()
	ctx, cancelFunc := context.WithCancel(ctx)

	handlerFunc := func(count int, ih *IntrHandler) {
		switch count {
		case 1:
			fmt.Println() // Prevent un-terminated ^C character in terminal

			ih.wg.Add(1)
			go func() {
				defer ih.wg.Done()
				cancelFunc()
			}()

		default:
			fmt.Println("Received another interrupt before graceful shutdown, terminating...")
			os.Exit(-1)
		}
	}

	intrh.Handle(handlerFunc, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM)

	return intrh, ctx
}
开发者ID:qnib,项目名称:go-ipfs,代码行数:26,代码来源:main.go


示例14: NewRegistry

func NewRegistry(cfg Config, appname, ip string, port int) (*Registry, error) {
	backendSpec, err := newBackendSpec(appname, ip, port)
	if err != nil {
		return nil, fmt.Errorf("Failed to create backend: err=(%s)", err)
	}

	if cfg.TTL <= 0 {
		cfg.TTL = defaultRegistrationTTL
	}

	etcdCfg := etcd.Config{Endpoints: []string{localEtcdProxy}}
	etcdClt, err := etcd.New(etcdCfg)
	if err != nil {
		return nil, err
	}
	ctx, cancelFunc := context.WithCancel(context.Background())
	go func() {
		for {
			err := etcdClt.AutoSync(ctx, 10*time.Second)
			if err == context.DeadlineExceeded || err == context.Canceled {
				break
			}
			fmt.Print(err)
		}
	}()
	etcdKeysAPI := etcd.NewKeysAPI(etcdClt)
	c := Registry{
		cfg:         cfg,
		backendSpec: backendSpec,
		etcdKeysAPI: etcdKeysAPI,
		ctx:         ctx,
		cancelFunc:  cancelFunc,
	}
	return &c, nil
}
开发者ID:vulcand,项目名称:vulcand,代码行数:35,代码来源:registry.go


示例15: TestDoContext

func TestDoContext(t *testing.T) {
	receivedCh := make(chan struct{})
	block := make(chan struct{})
	testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
		close(receivedCh)
		<-block
		w.WriteHeader(http.StatusOK)
	}))
	defer testServer.Close()
	defer close(block)

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	go func() {
		<-receivedCh
		cancel()
	}()

	c := testRESTClient(t, testServer)
	_, err := c.Verb("GET").
		Context(ctx).
		Prefix("foo").
		DoRaw()
	if err == nil {
		t.Fatal("Expected context cancellation error")
	}
}
开发者ID:kubernetes,项目名称:kubernetes,代码行数:28,代码来源:request_test.go


示例16: readPrep

func (dm *DagModifier) readPrep() error {
	err := dm.Sync()
	if err != nil {
		return err
	}

	if dm.read == nil {
		ctx, cancel := context.WithCancel(dm.ctx)
		dr, err := uio.NewDagReader(ctx, dm.curNode, dm.dagserv)
		if err != nil {
			return err
		}

		i, err := dr.Seek(int64(dm.curWrOff), os.SEEK_SET)
		if err != nil {
			return err
		}

		if i != int64(dm.curWrOff) {
			return ErrSeekFail
		}

		dm.readCancel = cancel
		dm.read = dr
	}

	return nil
}
开发者ID:qnib,项目名称:go-ipfs,代码行数:28,代码来源:dagmodifier.go


示例17: ExampleWithCancel

// This example demonstrate the use of a cancelable context preventing a
// goroutine leak. By the end of the example func's execution, the "count"
// goroutine is canceled.
func ExampleWithCancel() {
	count := func(ctx context.Context, dst chan<- int) {
		n := 1
		for {
			select {
			case dst <- n:
				n++
			case <-ctx.Done():
				return
			}
		}
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	ints := make(chan int)
	go count(ctx, ints)
	for n := range ints {
		fmt.Println(n)
		if n == 5 {
			return
		}
	}
	// Output:
	// 1
	// 2
	// 3
	// 4
	// 5
}
开发者ID:kuangchanglang,项目名称:go,代码行数:34,代码来源:example_test.go


示例18: TestCtxRead

func TestCtxRead(t *testing.T) {
	dserv := testu.GetDAGServ()

	n := testu.GetEmptyNode(t, dserv)
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	dagmod, err := NewDagModifier(ctx, n, dserv, testu.SizeSplitterGen(512))
	if err != nil {
		t.Fatal(err)
	}

	_, err = dagmod.Write([]byte{0, 1, 2, 3, 4, 5, 6, 7})
	if err != nil {
		t.Fatal(err)
	}
	dagmod.Seek(0, os.SEEK_SET)

	readBuf := make([]byte, 4)
	_, err = dagmod.CtxReadFull(ctx, readBuf)
	if err != nil {
		t.Fatal(err)
	}
	err = testu.ArrComp(readBuf, []byte{0, 1, 2, 3})
	if err != nil {
		t.Fatal(err)
	}
	// TODO(Kubuxu): context cancel case, I will do it after I figure out dagreader tests,
	// because this is exacelly the same.
}
开发者ID:VictorBjelkholm,项目名称:go-ipfs,代码行数:30,代码来源:dagmodifier_test.go


示例19: TestBasic

func TestBasic(t *testing.T) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	ds, rt := setupRoot(ctx, t)

	rootdir := rt.GetValue().(*Directory)

	// test making a basic dir
	_, err := rootdir.Mkdir("a")
	if err != nil {
		t.Fatal(err)
	}

	path := "a/b/c/d/e/f/g"
	d := mkdirP(t, rootdir, path)

	fi := getRandFile(t, ds, 1000)

	// test inserting that file
	err = d.AddChild("afile", fi)
	if err != nil {
		t.Fatal(err)
	}

	err = assertFileAtPath(ds, rootdir, fi, "a/b/c/d/e/f/g/afile")
	if err != nil {
		t.Fatal(err)
	}
}
开发者ID:VictorBjelkholm,项目名称:go-ipfs,代码行数:29,代码来源:mfs_test.go


示例20: BenchmarkDagmodWrite

func BenchmarkDagmodWrite(b *testing.B) {
	b.StopTimer()
	dserv := testu.GetDAGServ()
	n := testu.GetEmptyNode(b, dserv)
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	wrsize := 4096

	dagmod, err := NewDagModifier(ctx, n, dserv, testu.SizeSplitterGen(512))
	if err != nil {
		b.Fatal(err)
	}

	buf := make([]byte, b.N*wrsize)
	u.NewTimeSeededRand().Read(buf)
	b.StartTimer()
	b.SetBytes(int64(wrsize))
	for i := 0; i < b.N; i++ {
		n, err := dagmod.Write(buf[i*wrsize : (i+1)*wrsize])
		if err != nil {
			b.Fatal(err)
		}
		if n != wrsize {
			b.Fatal("Wrote bad size")
		}
	}
}
开发者ID:VictorBjelkholm,项目名称:go-ipfs,代码行数:28,代码来源:dagmodifier_test.go



注:本文中的context.WithCancel函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang context.WithDeadline函数代码示例发布时间:2022-05-24
下一篇:
Golang context.TODO函数代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap