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


Golang sync.RWMutex類代碼示例

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


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

示例1: BenchmarkRWMutexR1

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

示例2: getJob

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

	vars := mux.Vars(r)
	jobId := vars["id"]

	job, err := c.store.GetJob(jobId)
	if err != nil {
		if serr, ok := err.(*StoreError); ok {
			if serr.Code == ErrNotFound {
				w.Header().Set("Content-Type", "application/json; charset=UTF-8")
				w.WriteHeader(http.StatusNotFound)
				return
			}
		}
		log.Printf("Error: %s", 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")
	if err := json.NewEncoder(w).Encode(job); err != nil {
		log.Printf("Error: %s", err)
		panic(err)
	}
	w.WriteHeader(http.StatusOK)
}
開發者ID:lucmichalski,項目名稱:taurus,代碼行數:30,代碼來源:api.go

示例3: Scrape

// Scrape reports scrape for one or more files, using HTTP format
func (h HTTPTracker) Scrape(files []data.FileRecord) []byte {
	// Response struct
	scrape := scrapeResponse{
		Files: make(map[string]scrapeFile),
	}

	// WaitGroup to wait for all scrape file entries to be generated
	var wg sync.WaitGroup
	wg.Add(len(files))

	// Mutex for safe locking on map writes
	var mutex sync.RWMutex

	// Iterate all files in parallel
	for _, f := range files {
		go func(f data.FileRecord, scrape *scrapeResponse, mutex *sync.RWMutex, wg *sync.WaitGroup) {
			// Generate scrapeFile struct
			fileInfo := scrapeFile{}
			var err error

			// Seeders count
			fileInfo.Complete, err = f.Seeders()
			if err != nil {
				log.Println(err.Error())
			}

			// Completion count
			fileInfo.Downloaded, err = f.Completed()
			if err != nil {
				log.Println(err.Error())
			}

			// Leechers count
			fileInfo.Incomplete, err = f.Leechers()
			if err != nil {
				log.Println(err.Error())
			}

			// Add hash and file info to map
			mutex.Lock()
			scrape.Files[f.InfoHash] = fileInfo
			mutex.Unlock()

			// Inform waitgroup that this file is ready
			wg.Done()
		}(f, &scrape, &mutex, &wg)
	}

	// Wait for all information to be generated
	wg.Wait()

	// Marshal struct into bencode
	buf := bytes.NewBuffer(make([]byte, 0))
	if err := bencode.Marshal(buf, scrape); err != nil {
		log.Println(err.Error())
		return h.Error(ErrScrapeFailure.Error())
	}

	return buf.Bytes()
}
開發者ID:gernest,項目名稱:goat,代碼行數:61,代碼來源:httpTracker.go

示例4: BenchmarkRWMutexLock

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

示例5: 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

示例6: 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

示例7: New

func New(wd string, ss Strategizer, gro ...GrabberOption) (*Grabber, error) {
	if wd == "" {
		return nil, MissingWorkDirError
	}
	mx := new(sync.RWMutex)
	g := &Grabber{
		wd:          wd,
		s:           ss,
		writeState:  mx,
		readState:   mx.RLocker(),
		qIn:         make(chan Segmenter, 100), // TODO(negz): Determine best buffer len.
		qOut:        make(chan Segmenter, 100),
		maxRetry:    3,
		doneMx:      new(sync.Mutex),
		pp:          make(chan bool),
		decoder:     yenc.NewDecoder, // TODO(negz): Detect encoding.
		fileCreator: createSegmentFile,
		grabT:       new(tomb.Tomb),
		enqueueT:    new(tomb.Tomb),
	}
	for _, o := range gro {
		if err := o(g); err != nil {
			return nil, err
		}
	}
	if g.name == "" {
		return nil, MissingNameError
	}
	g.hash = util.HashString(g.name)
	return g, nil
}
開發者ID:frank3nst3in,項目名稱:grabby,代碼行數:31,代碼來源:grabber.go

示例8: ReadFile

//讀文件
func (helper *FileHelper) ReadFile(filename string) (string, error) {
	lock := new(sync.RWMutex)
	lock.RLock()

	var content string
	file, err := os.Open(filename)

	if err != nil {
		fmt.Println("file open error:", err)
		return content, err
	}

	reader := bufio.NewReader(file)
	for {
		line, _, err := reader.ReadLine()
		if err != nil {
			break
		}

		content += string(line) + ","
	}

	content = strings.TrimRight(content, ",")
	file.Close()
	lock.RUnlock()

	fmt.Println(content)
	return content, err
}
開發者ID:jessehua,項目名稱:nsqclient,代碼行數:30,代碼來源:FileHelper.go

示例9: 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

示例10: UnlockPolicy

func (lm *lockManager) UnlockPolicy(lock *sync.RWMutex, lockType bool) {
	if lockType == exclusive {
		lock.Unlock()
	} else {
		lock.RUnlock()
	}
}
開發者ID:chrishoffman,項目名稱:vault,代碼行數:7,代碼來源:lock_manager.go

示例11: main

func main() {
	var l *sync.RWMutex
	l = new(sync.RWMutex)
	l.RUnlock()
	fmt.Println("l")
	l.RLock()
}
開發者ID:r00tjimmy,項目名稱:codeBox,代碼行數:7,代碼來源:sync_rwmutex.go

示例12: checksyncstatus

func (fs Filesystem) checksyncstatus(path string) error {
	path = strings.TrimPrefix(path, "/home/minio")
	path = "mnt/minio/data" + path
	var lock sync.RWMutex
	nosync := make(map[string]bool)
	kubeClient, err := client.NewInCluster()
	if err != nil {
		return fmt.Errorf("unable to create client")
	}
	pclient := kubeClient.Pods("default")
	selector, _ := labels.Parse("app=minio-sync")
	list, err := pclient.List(selector, nil)
	if err != nil {
		return fmt.Errorf("list pods failed")
	}
	for _, pod := range list.Items {
		fmt.Println(pod.Status.PodIP)
		if pod.Status.Phase == "Running" {
			nosync[pod.Status.PodIP] = false
		}
	}
	allsync := true
	var duration float64
	for duration = 1; duration < 60; duration++ {
		timeperiod := time.Duration(time.Second * time.Duration(duration))
		fmt.Println(timeperiod)
		time.Sleep(timeperiod)
		var wg sync.WaitGroup
		wg.Add(len(nosync))
		for ip, sync := range nosync {
			go func(ip string, sync bool) {
				if !sync {
					if doCurl("http://" + ip + ":3000/" + path) {
						lock.Lock()
						nosync[ip] = true
						lock.Unlock()
					} else {
						if allsync {
							allsync = false
						}
					}
				}
				wg.Done()
			}(ip, sync)
		}
		wg.Wait()
		if allsync {
			break
		}
		allsync = true
	}
	for _, sync := range nosync {
		if !sync {
			return fmt.Errorf("sync failed took more time ")
		}
	}
	return nil

}
開發者ID:smothiki,項目名稱:minio.io,代碼行數:59,代碼來源:checksync.go

示例13: BenchmarkConcurrentRWMutex

func BenchmarkConcurrentRWMutex(b *testing.B) {
	var mu sync.RWMutex
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			mu.RLock()
			mu.RUnlock()
		}
	})
}
開發者ID:funkygao,項目名稱:gafka,代碼行數:9,代碼來源:server_test.go

示例14: BenchmarkRWMutexW

func BenchmarkRWMutexW(b *testing.B) {
	b.SetParallelism(10)
	var mtx sync.RWMutex
	b.RunParallel(func(pb *testing.PB) {
		for pb.Next() {
			mtx.Lock()
			mtx.Unlock()
		}
	})
}
開發者ID:twmb,項目名稱:dash,代碼行數:10,代碼來源:block_test.go

示例15: chromeProcessesCleaner

// SKPs are captured in parallel leading to multiple chrome instances coming up
// at the same time, when there are crashes chrome processes stick around which
// can severely impact the machine's performance. To stop this from
// happening chrome zombie processes are periodically killed.
func chromeProcessesCleaner(mutex *sync.RWMutex) {
	for _ = range time.Tick(*chromeCleanerTimer) {
		glog.Info("The chromeProcessesCleaner goroutine has started")
		glog.Info("Waiting for all existing tasks to complete before killing zombie chrome processes")
		mutex.Lock()
		skutil.LogErr(util.ExecuteCmd("pkill", []string{"-9", "chrome"}, []string{},
			util.PKILL_TIMEOUT, nil, nil))
		mutex.Unlock()
	}
}
開發者ID:Tiger66639,項目名稱:skia-buildbot,代碼行數:14,代碼來源:main.go


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