package main

import (
	"fmt"
	"sync"
)

var l sync.Mutex
var a string

func f() {
	a = "hello, world"
	l.Unlock()
}

//还是需要加锁的!!!
type testClass struct {
	mutex sync.Mutex
	x     []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 int

var x2 chan int

func 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 testClass
	txtcls.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个协程同时对一个对象指针变量进行读操作的时候需要进行加锁

那么不加有什么问题呢:

会出现打印出只有一个变量的情况