Golang、python线程小列子。。。。。。

天天成长一小步,积累下来就是一大步。python

在GO中,开启15个线程,每一个线程把全局变量遍历增长100000次,所以预测结果是 15*100000=1500000.app

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)
      }
   }
}

可是最终的结果,406527ui

说明须要加锁。线程

func Count1(i int, ch chan int) {
   m.Lock()
   for j := 0; j < 100000; j++ {
      cccc = cccc + 1
   }
   ch <- cccc
   m.Unlock()
}

最终输出:1500000get

 

python中:一样方式实现,也不行。thread

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)

输出结果:3004737变量

说明也须要加锁:select

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)

输出1500000遍历

OK,加锁的小列子。di

相关文章
相关标签/搜索