本文整理匯總了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()
}
}
示例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)
}
示例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()
}
示例4: BenchmarkRWMutexLock
func BenchmarkRWMutexLock(b *testing.B) {
var l sync.RWMutex
for i := 0; i < b.N; i++ {
l.Lock()
l.Unlock()
}
}
示例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)
}
示例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()
}
}
示例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
}
示例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
}
示例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()
}
}
}
示例10: UnlockPolicy
func (lm *lockManager) UnlockPolicy(lock *sync.RWMutex, lockType bool) {
if lockType == exclusive {
lock.Unlock()
} else {
lock.RUnlock()
}
}
示例11: main
func main() {
var l *sync.RWMutex
l = new(sync.RWMutex)
l.RUnlock()
fmt.Println("l")
l.RLock()
}
示例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
}
示例13: BenchmarkConcurrentRWMutex
func BenchmarkConcurrentRWMutex(b *testing.B) {
var mu sync.RWMutex
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
mu.RLock()
mu.RUnlock()
}
})
}
示例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()
}
})
}
示例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()
}
}