Golang and python thread details and simple examples
- 2020-05-30 20:32:13
- OfStack
Golang and python threads details and simple examples
In GO, 15 threads are started and each thread iterates the global variable 100,000 times, so the predicted result is 15* 100,000 = 1,500,000.
var sum int
var cccc int
var m *sync.Mutex
func Count1(i int, ch chan int) {
for j := 0; j < 100000; j++ {
cccc = cccc + 1
}
ch <- cccc
}
func main() {
m = new(sync.Mutex)
ch := make(chan int, 15)
for i := 0; i < 15; i++ {
go Count1(i, ch)
}
for i := 0; i < 15; i++ {
select {
case msg := <-ch:
fmt.Println(msg)
}
}
}
But the end result, 406,527
It says it needs to be locked.
func Count1(i int, ch chan int) {
m.Lock()
for j := 0; j < 100000; j++ {
cccc = cccc + 1
}
ch <- cccc
m.Unlock()
}
Final output: 1500000
python: same way, no.
count = 0
def sumCount(temp):
global count
for i in range(temp):
count = count + 1
li = []
for i in range(15):
th = threading.Thread(target=sumCount, args=(1000000,))
th.start()
li.append(th)
for i in li:
i.join()
print(count)
Output result: 3004737
Note also need to be locked:
mutex = threading.Lock()
count = 0
def sumCount(temp):
global count
mutex.acquire()
for i in range(temp):
count = count + 1
mutex.release()
li = []
for i in range(15):
th = threading.Thread(target=sumCount, args=(1000000,))
th.start()
li.append(th)
for i in li:
i.join()
print(count)
The output of 1500000
OK, small column with locks.
Thank you for reading, I hope to help you, thank you for your support of this site!