Golang与python线程详解及简单实例

yipeiwu_com6年前Python基础

Golang与python线程详解及简单实例

在GO中,开启15个线程,每个线程把全局变量遍历增加100000次,因此预测结果是 15*100000=1500000.

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

但是最终的结果,406527

说明需要加锁。

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

最终输出:1500000

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

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

说明也需要加锁:

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,加锁的小列子。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关文章

Python循环实现n的全排列功能

描述: 输入一个大于0的整数n,输出1到n的全排列: 例如: n=3,输出[[3, 2, 1], [2, 3, 1], [2, 1, 3], [3, 1, 2], [1, 3, 2]...

对pytorch中的梯度更新方法详解

背景 使用pytorch时,有一个yolov3的bug,我认为涉及到学习率的调整。收集到tencent yolov3和mxnet开源的yolov3,两个优化器中的学习率设置不一样,而且使...

python制作mysql数据迁移脚本

用python写了个数据迁移脚本,主要是利用从库将大的静态表导出表空间,载导入到目标实例中。 #!/usr/bin/env python3 #-*- coding:utf8 -*-...

netbeans7安装python插件的方法图解

netbeans7安装python插件的方法图解

我们可以手动来添加地址和安装。如图所示: 方法:NetBeans界面,“工具”->“插件”, 点击“设置”->点击“添加”,然后 添加一个更新中心地址 ,名称可以任意,U...

如何解决django-celery启动后迅速关闭

日志中也没有打印什么明显的错误,只是显示连接了rabbitmq后就关闭了 [2019-09-11 06:08:45,729: INFO/Beat] beat: Starting......