Golang channel and mutex selection, performance is similar

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Go official should be more recommended to use Chan
Https://github.com/golang/go/wiki/MutexOrChannel

The following code is used to test performance-not to make sure that the idea is correct.

 PackageMainImport("FMT"    "Sync"    "Time")typeOpstruct{KeyintValint}varLock sync. MutexvarM1Map[int]intvarM2Map[int]intvarMaxint=50000funcUpdate_map_by_mutex (iint) {lock. Lock () m1[i] = iif Len(m1) = = max {fmt. Printf ("%s Mutex finish\n", time. Now ())} lock. Unlock ()}varChChanOpfuncUpdate_map_by_chan (iint) {ch <-op{key:i, Val:i}}funcWait_for_chan (MMap[int]int) { for{Select{ CaseOP: = <-ch:m[op.key] = Op.valif Len(m2) = = max {fmt. Printf ("%s Chan finish\n", time. Now ())return}        }    }}funcMain () {m1 = Make(Map[int]int, max) m2 = Make(Map[int]int, max) ch = Make(ChanOP)GoWait_for_chan (m2) forI: =0; i < Max; i++ {GoUpdate_map_by_chan (i)GoUpdate_map_by_mutex (i)} time. Sleep (time. Second *1)}

Output Result:

2015-11-17 17:08:18.06992 +0800 CST Mutex finish
2015-11-17 17:08:18.0709215 +0800 CST chan finish

Mutex performance is slightly better, but Chan is more go, more recommended.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.