本文整理匯總了Golang中context.WithCancel函數的典型用法代碼示例。如果您正苦於以下問題:Golang WithCancel函數的具體用法?Golang WithCancel怎麽用?Golang WithCancel使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了WithCancel函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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()
}
示例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)
}
}
}
示例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,
}
}
示例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
}
示例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
}
示例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")
}
示例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)
}
示例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)
}
}
示例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")
}
}
示例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)
}
}
}
示例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
}
示例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"
}
示例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
}
示例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
}
示例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")
}
}