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


Golang RWMutex.Unlock方法代碼示例

本文整理匯總了Golang中sync.RWMutex.Unlock方法的典型用法代碼示例。如果您正苦於以下問題:Golang RWMutex.Unlock方法的具體用法?Golang RWMutex.Unlock怎麽用?Golang RWMutex.Unlock使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在sync.RWMutex的用法示例。


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

示例1: TestStream_Open_WithOp

func TestStream_Open_WithOp(t *testing.T) {
	src := newStrSrc([]string{"HELLO", "WORLD", "HOW", "ARE", "YOU"})
	snk := newStrSink()
	op1 := api.UnFunc(func(ctx context.Context, data interface{}) interface{} {
		str := data.(string)
		return len(str)
	})

	var m sync.RWMutex
	runeCount := 0
	op2 := api.UnFunc(func(ctx context.Context, data interface{}) interface{} {
		length := data.(int)
		m.Lock()
		runeCount += length
		m.Unlock()
		return nil
	})

	strm := New().From(src).Transform(op1).Transform(op2).To(snk)
	select {
	case err := <-strm.Open():
		if err != nil {
			t.Fatal(err)
		}
	case <-time.After(50 * time.Millisecond):
		t.Fatal("Waited too long ...")
	}
	m.RLock()
	if runeCount != 19 {
		t.Fatal("Data not streaming, runeCount 19, got ", runeCount)
	}
	m.RUnlock()
}
開發者ID:vladimirvivien,項目名稱:automi,代碼行數:33,代碼來源:stream_test.go

示例2: startJob

func startJob(c *Context, w http.ResponseWriter, r *http.Request) {
	var mu sync.RWMutex
	mu.Lock()
	defer mu.Unlock()

	var job Job
	err := json.NewDecoder(r.Body).Decode(&job)
	if err != nil {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusInternalServerError)
		log.Printf("Error: %s", err)
		return
	}

	job.State = PENDING
	log.Printf("Submitting Job %s", job.Id)
	err = c.store.AddJob(&job)
	if err != nil {
		if serr, ok := err.(*StoreError); ok {
			if serr.Code == ErrExists {
				w.Header().Set("Content-Type", "application/json; charset=UTF-8")
				w.WriteHeader(http.StatusNotModified)
				return
			}
		}
		log.Printf("Could not store job %s: %s", job.Id, err)
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json; charset=UTF-8")
	w.WriteHeader(http.StatusOK)
}
開發者ID:lucmichalski,項目名稱:taurus,代碼行數:34,代碼來源:api.go

示例3: Task

func Task(f func(in Receiver, out Sender)) Sender {
	var running bool
	var l sync.RWMutex
	inR, inW := Pipe()
	outR, outW := Pipe()
	obj := NewServer()
	obj.OnAttach(Handler(func(msg *Message) error {
		msg.Ret.Send(&Message{Verb: Ack, Ret: inW})
		fmt.Printf("copying task output from %#v to %#v\n", outR, msg.Ret)
		defer fmt.Printf("(DONE) copying task output from %#v to %#v\n", outR, msg.Ret)
		Copy(msg.Ret, outR)
		return nil
	}))
	obj.OnStart(Handler(func(msg *Message) error {
		l.RLock()
		r := running
		l.RUnlock()
		if r {
			return fmt.Errorf("already running")
		}
		l.Lock()
		go f(inR, outW)
		running = true
		l.Unlock()
		msg.Ret.Send(&Message{Verb: Ack})
		return nil
	}))
	return obj
}
開發者ID:RubanDeventhiran,項目名稱:libswarm,代碼行數:29,代碼來源:task.go

示例4: TestSendReceiveWithWait

func TestSendReceiveWithWait(t *testing.T) {
	conn := NewConn()
	conn.ReceiveWait = true

	conn.Command("HGETALL", "person:1").ExpectMap(map[string]string{
		"name": "Mr. Johson",
		"age":  "42",
	})
	conn.Command("HGETALL", "person:2").ExpectMap(map[string]string{
		"name": "Ms. Jennifer",
		"age":  "28",
	})

	ids := []string{"1", "2"}
	for _, id := range ids {
		conn.Send("HGETALL", fmt.Sprintf("person:%s", id))
	}

	var people []Person
	var peopleLock sync.RWMutex

	go func() {
		for i := 0; i < len(ids); i++ {
			values, err := redis.Values(conn.Receive())
			if err != nil {
				t.Fatal(err)
			}

			var person Person
			err = redis.ScanStruct(values, &person)
			if err != nil {
				t.Fatal(err)
			}

			peopleLock.Lock()
			people = append(people, person)
			peopleLock.Unlock()
		}
	}()

	for i := 0; i < len(ids); i++ {
		conn.ReceiveNow <- true
	}
	time.Sleep(10 * time.Millisecond)

	peopleLock.RLock()
	defer peopleLock.RUnlock()

	if len(people) != 2 {
		t.Fatalf("Wrong number of people. Expected '2' and got '%d'", len(people))
	}

	if people[0].Name != "Mr. Johson" || people[1].Name != "Ms. Jennifer" {
		t.Error("People name order are wrong")
	}

	if people[0].Age != 42 || people[1].Age != 28 {
		t.Error("People age order are wrong")
	}
}
開發者ID:ttaylorr,項目名稱:redigomock,代碼行數:60,代碼來源:redigomock_test.go

示例5: compileFieldDynamic

func compileFieldDynamic(name string, args []parse.Node) lookupFn {
	type key struct {
		valueType reflect.Type
		finalType reflect.Type
	}

	var m sync.RWMutex
	cache := make(map[key]lookupFn)
	return func(s state, value reflect.Value, final interface{}) reflect.Value {
		valueType := value.Elem().Type()
		var finalType reflect.Type
		if v := reflect.ValueOf(final); v.IsValid() {
			finalType = v.Type()
		}

		k := key{valueType, finalType}
		m.RLock()
		f, exist := cache[k]
		m.RUnlock()
		if !exist {
			f, _ = compileField(valueType, name, args, finalType)
			m.Lock()
			cache[k] = f
			m.Unlock()
		}
		return f(s, value.Elem(), final)
	}
}
開發者ID:rui314,項目名稱:template,代碼行數:28,代碼來源:template.go

示例6: main

func main() {
	Case := Init(6)
	fmt.Printf("DEADLOCK\n")

	c := make(chan int)
	var mu sync.RWMutex
	done := make(chan bool)
	go func() {
		time.Sleep(sleep3[Case][0])
		mu.RLock()
		c <- 1
		mu.RUnlock()
		done <- true
	}()
	go func() {
		time.Sleep(sleep3[Case][1])
		mu.RLock()
		<-c
		mu.RUnlock()
		done <- true
	}()
	time.Sleep(sleep3[Case][2])
	mu.Lock()
	mu.Unlock()
	<-done
	<-done
}
開發者ID:dvyukov,項目名稱:go-conc,代碼行數:27,代碼來源:chan_rwmutex.go

示例7: compileVariableNode

func compileVariableNode(node *parse.VariableNode, dotType reflect.Type, args []parse.Node, finalType reflect.Type) (cmd command, retType reflect.Type) {
	var mu sync.RWMutex
	type key struct {
		dotType, finalType reflect.Type
	}
	cache := make(map[key]command)

	name := node.Ident[0]
	cmd = func(s state, dot, final interface{}) interface{} {
		value := s.varValue(name)
		if len(node.Ident) == 1 {
			return value.Interface()
		}

		if dotType == nil {
			dotType = reflect.ValueOf(dot).Type()
		}
		if finalType == nil && final != nil {
			finalType = reflect.ValueOf(final).Type()
		}
		k := key{dotType, finalType}

		mu.RLock()
		f, exist := cache[k]
		mu.RUnlock()
		if !exist {
			f, _ = compileFieldChain(node.Ident[1:], dotType, args, finalType)
			mu.Lock()
			cache[k] = f
			mu.Unlock()
		}
		return f(s, dot, value)
	}
	return
}
開發者ID:rui314,項目名稱:template,代碼行數:35,代碼來源:template.go

示例8: GetCache

//GetCache checks  nodes in lookuptable have the cache.
//if found gets records.
func GetCache(background bool, c *thread.Cache) bool {
	const searchDepth = 5 // Search node size
	ns := manager.NodesForGet(c.Datfile, searchDepth)
	found := false
	var wg sync.WaitGroup
	var mutex sync.RWMutex
	dm := NewManger(c)
	for _, n := range ns {
		wg.Add(1)
		go func(n *node.Node) {
			defer wg.Done()
			if !headWithRange(n, c, dm) {
				return
			}
			if getWithRange(n, c, dm) {
				mutex.Lock()
				found = true
				mutex.Unlock()
				return
			}
		}(n)
	}
	if background {
		bg(c, &wg)
	} else {
		wg.Wait()
	}
	mutex.RLock()
	defer mutex.RUnlock()
	return found
}
開發者ID:shingetsu-gou,項目名稱:shingetsu-gou,代碼行數:33,代碼來源:download.go

示例9: BenchmarkRWMutexW1

func BenchmarkRWMutexW1(b *testing.B) {
	var mtx sync.RWMutex
	for i := 0; i < b.N; i++ {
		mtx.Lock()
		mtx.Unlock()
	}
}
開發者ID:twmb,項目名稱:dash,代碼行數:7,代碼來源:block_test.go

示例10: TestCacheWatcherCleanupNotBlockedByResult

// verifies the cacheWatcher.process goroutine is properly cleaned up even if
// the writes to cacheWatcher.result channel is blocked.
func TestCacheWatcherCleanupNotBlockedByResult(t *testing.T) {
	var lock sync.RWMutex
	count := 0
	filter := func(string, labels.Set, fields.Set) bool { return true }
	forget := func(bool) {
		lock.Lock()
		defer lock.Unlock()
		count++
	}
	initEvents := []watchCacheEvent{
		{Object: &api.Pod{}},
		{Object: &api.Pod{}},
	}
	// set the size of the buffer of w.result to 0, so that the writes to
	// w.result is blocked.
	w := newCacheWatcher(0, 0, initEvents, filter, forget)
	w.Stop()
	if err := wait.PollImmediate(1*time.Second, 5*time.Second, func() (bool, error) {
		lock.RLock()
		defer lock.RUnlock()
		return count == 2, nil
	}); err != nil {
		t.Fatalf("expected forget() to be called twice, because sendWatchCacheEvent should not be blocked by the result channel: %v", err)
	}
}
開發者ID:jbeda,項目名稱:kubernetes,代碼行數:27,代碼來源:cacher_whitebox_test.go

示例11: TestRaceRWMutexMultipleReaders

func TestRaceRWMutexMultipleReaders(t *testing.T) {
	var mu sync.RWMutex
	var x, y int64 = 0, 1
	ch := make(chan bool, 3)
	go func() {
		mu.Lock()
		defer mu.Unlock()
		x = 2
		ch <- true
	}()
	go func() {
		mu.RLock()
		y = x + 1
		mu.RUnlock()
		ch <- true
	}()
	go func() {
		mu.RLock()
		y = x + 2
		mu.RUnlock()
		ch <- true
	}()
	<-ch
	<-ch
	<-ch
	_ = y
}
開發者ID:h8liu,項目名稱:golang,代碼行數:27,代碼來源:rwmutex_test.go

示例12: TestNoRaceRWMutexMultipleReaders

func TestNoRaceRWMutexMultipleReaders(t *testing.T) {
	var mu sync.RWMutex
	x := int64(0)
	ch := make(chan bool, 3)
	go func() {
		mu.Lock()
		defer mu.Unlock()
		x = 2
		ch <- true
	}()
	go func() {
		mu.RLock()
		y := x + 1
		_ = y
		mu.RUnlock()
		ch <- true
	}()
	go func() {
		mu.RLock()
		y := x + 2
		_ = y
		mu.RUnlock()
		ch <- true
	}()
	<-ch
	<-ch
	<-ch
}
開發者ID:h8liu,項目名稱:golang,代碼行數:28,代碼來源:rwmutex_test.go

示例13: main

func main() {
	Case := Init(6)
	fmt.Printf("DEADLOCK\n")

	c := make(chan int)
	var mu sync.RWMutex
	done := make(chan bool)
	go func() {
		time.Sleep(sleep3[Case][0])
		mu.RLock()
		c <- 1
		mu.RUnlock()
		done <- true
	}()
	go func() {
		time.Sleep(sleep3[Case][1])
		mu.RLock()
	loop:
		for {
			select {
			case <-c:
				break loop
			case <-time.After(time.Millisecond):
			}
		}
		mu.RUnlock()
		done <- true
	}()
	time.Sleep(sleep3[Case][2])
	mu.Lock()
	mu.Unlock()
	<-done
	<-done
}
開發者ID:dvyukov,項目名稱:go-conc,代碼行數:34,代碼來源:select_rwmutex.go

示例14: doRunCommand

func doRunCommand(c *cli.Context) {
	config := ParseConfigOrDie(c.GlobalString("config"))
	client := github.NewClient(config.GitHubAPIToken)

	// Create and start monitoring queues.
	lock := sync.RWMutex{}
	queues := createQueues(client, config, &lock)
	stopChan := monitorQueues(queues)

	// Graceful stop on SIGTERM and SIGINT.
	s := make(chan os.Signal, 64)
	signal.Notify(s, syscall.SIGTERM, syscall.SIGINT)

	// Compute next tick time for the synchronization event.
	nextTickTime := resetNextTickTime(config.PeriodicSync)
	for {
		select {
		case <-stopChan:
			log.Debug("All queues exited")
			return
		case sig := <-s:
			log.WithField("signal", sig).Debug("received signal")
			for _, q := range queues {
				q.Consumer.Stop()
			}
		case <-time.After(nextTickTime):
			lock.Lock() // Take a write lock, which pauses all queue processing.
			log.Infof("Starting periodic sync")
			runPeriodicSync(client, config)
			nextTickTime = resetNextTickTime(config.PeriodicSync)
			lock.Unlock()
		}
	}
}
開發者ID:asemt,項目名稱:vossibility-collector,代碼行數:34,代碼來源:run.go

示例15: BenchmarkMutableCopy

// BenchmarkMutableCopy benchmarks how long it takes to copy a mutable treap
// to another one when it contains 'numTicketKeys' entries.
func BenchmarkMutableCopy(b *testing.B) {
	// Populate mutable treap with a bunch of key/value pairs.
	testTreap := NewMutable()
	ticketKeys := genTicketKeys()
	for j := 0; j < len(ticketKeys); j++ {
		hashBytes := ticketKeys[j]
		value := &Value{Height: uint32(j)}
		testTreap.Put(hashBytes, value)
	}

	b.ReportAllocs()
	b.ResetTimer()

	// Copying a mutable treap requires iterating all of the entries and
	// populating them into a new treap all with a lock held for concurrency
	// safety.
	var mtx sync.RWMutex
	for i := 0; i < b.N; i++ {
		benchTreap := NewMutable()
		mtx.Lock()
		testTreap.ForEach(func(k Key, v *Value) bool {
			benchTreap.Put(k, v)
			return true
		})
		mtx.Unlock()
	}
}
開發者ID:decred,項目名稱:dcrd,代碼行數:29,代碼來源:benchmark_test.go


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