標籤:defer import select pack str 操作 def port 有一個
package mainimport ("fmt""sync")var l sync.Mutexvar a stringfunc f() {a = "hello, world"l.Unlock()}//還是需要加鎖的!!!type testClass struct {mutex sync.Mutexx []byte}func (this *testClass) init() {this.x = make([]byte, 0)}func (this *testClass) addx(val byte) {this.mutex.Lock()defer this.mutex.Unlock()this.x = append(this.x, val)}func (this *testClass) print() {fmt.Println(this.x)}var x1 chan intvar x2 chan intfunc f1(txtcls *testClass) {txtcls.addx(‘x‘)x1 <- 1}func f2(txtcls *testClass) {txtcls.addx(‘y‘)x2 <- 1}func main() {x1 = make(chan int)x2 = make(chan int)var txtcls testClasstxtcls.init()go f1(&txtcls)go f2(&txtcls)select {case <-x1:fmt.Println("xxxxx")}select {case <-x2:fmt.Println("yyyyy")}txtcls.print()/*l.Lock()go f()l.Lock()print(a)l.Unlock()*/}
以上代碼說明如下問題,2個協程同時對一個對象指標變數進行讀操作的時候需要進行加鎖
那麼不加有什麼問題呢:
會出現列印出只有一個變數的情況
go語言 加鎖的問題