Python 限制线程的最大数量的方法(Semaphore)

yipeiwu_com6年前Python基础

如下所示:

import threading
import time
 
sem=threading.Semaphore(4) #限制线程的最大数量为4个
 
def gothread():
  with sem: #锁定线程的最大数量
    for i in range(8):
      print(threading.current_thread().name,i)
      time.sleep(1)
 
for i in range(5):
  threading.Thread(target=gothread).start()

以上这篇Python 限制线程的最大数量的方法(Semaphore)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python查询IP地址归属完整代码

本文实例为大家分享了Python查询IP地址归属的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python # -*- coding: utf-8 -*- #...

Python中的引用和拷贝浅析

If an object's value can be modified, the object is said to be mutable. If the value cannot b...

详解Python nose单元测试框架的安装与使用

详解Python nose单元测试框架的安装与使用

本文介绍了Python nose单元测试框架的安装与使用 ,分享给大家,具体如下: 安装(Python2下安装) pip install nose 原理与命名规则 Nose会自动查...

关于pytorch中全连接神经网络搭建两种模式详解

pytorch搭建神经网络是很简单明了的,这里介绍两种自己常用的搭建模式: import torch import torch.nn as nn first: class NN...

Python判断字符串是否为字母或者数字(浮点数)的多种方法

str为字符串s为字符串 str.isalnum() 所有字符都是数字或者字母 str.isalpha() 所有字符都是字母 str.isdigit() 所有字符都是数字 str.iss...