1024programmer Java Go shared memory mechanism

Go shared memory mechanism

Lock example in Java

Insert picture description here

Lock concept in Go

package main import ("sync ""testing""time"
)func TestCounter(t *testing.T) {counter := 0for i := 0; i <5000; i++ {go func() {counter++}()}time.Sleep( 1*time.Second)t.Logf("counter = %d", counter)
}func TestCounterThreadSafe(t *testing.T) {counter := 0var mut sync.Mutexfor i := 0; i <5000; i++ {go func() {defer func() {mut.Unlock()}()mut.Lock()counter++}()}time.Sleep(1 *time.Second)t.Logf("counter = %d" , counter)
}func TestCounterWaitGroup(t *testing.T) {var wg sync.WaitGroupvar mut

This article is from the internet and does not represent1024programmerPosition, please indicate the source when reprinting:https://www.1024programmer.com/724843

author: admin

Previous article
Next article

Leave a Reply

Your email address will not be published. Required fields are marked *

Contact Us

Contact us

181-3619-1160

Online consultation: QQ交谈

E-mail: [email protected]

Working hours: Monday to Friday, 9:00-17:30, holidays off

Follow wechat
Scan wechat and follow us

Scan wechat and follow us

Follow Weibo
Back to top
首页
微信
电话
搜索