# python的多线程适合计算密集操作_初学Python——线程

Python中如何使用多线程？

import time

# 直接调用

def run(n):

time.sleep(2)

if __name__ == "__main__":

t1.start() # 启动线程

t2.start()

# 现在同时启动50个线程

start = time.time()

for i in range(50):

t.start()

end = time.time()

cost = end - start

print("cost time:",cost)

import time

'''继承式调用'''

def __init__(self,n):

self.n = n

def run(self):

time.sleep(1)

if __name__ == "__main__":

start = time.time()

obj = []

for i in range(50):

t.start()

end = time.time()

cost = end - start

print("cost time:",cost)

import time

'''继承式调用'''

def __init__(self,n):

self.n = n

def run(self):

time.sleep(1)

if __name__ == "__main__":

start = time.time()

obj = []

for i in range(50):

t.start()

obj.append(t) # 为了不阻塞后面线程的启动，现将其加入列表

for j in obj:

j.join()

end = time.time()

cost = end - start

print("cost time:",cost)

join等待

def run():

lock.acquire() # 获取锁

global num

num += 1

lock.release() # 释放锁

time.sleep(1)

if __name__ == "__main__":

num = 0

obj = []

start = time.time()

for i in range(1000):

t.start()

obj.append(t)

for j in obj:

j.join()

end = time.time()

cost = end - start

print("cost time:",cost)

print("num:",num)

def run1():

print("grab the first part data")

lock.acquire()

global num

num += 1

lock.release()

return num

def run2():

print("grab the second part data")

lock.acquire()

global num2

num2 += 1

lock.release()

return num2

def run3():

lock.acquire()

res = run1()

print('--------between run1 and run2-----')

res2 = run2()

lock.release()

print(res, res2)

if __name__ == '__main__':

num, num2 = 0, 0

for i in range(10):

t.start()

else:

print(num, num2)

def run(n):

semaphore.acquire()

time.sleep(1)

semaphore.release()

if __name__ == '__main__':

for i in range(20):

t.start()

else:

Timer

def hello():

print("hello, world")

t = Timer(30.0, hello)

t.start() # 30秒后执行此线程

Timer

Event

set() 设置标志位

clear()清空标志位

wait()如果已经设置标志位不会阻塞，如果没有设置标志位则产生阻塞

isSet() 判定是否设置了标志位。

import time

import random

def light():

"红绿灯"

while True:

count = 1

event.set() # 标志位设定了，wait就不阻塞 #绿灯状态

while True:

if count == 1:

print('\033[42;1m--green light on---\033[0m')

time.sleep(10)

count = 2

elif count == 2:

print('\033[43;1m--yellow light on---\033[0m')

time.sleep(2)

count = 3

elif count == 3:

event.clear() # 标志位被清空，wait()阻塞

print('\033[41;1m--red light on---\033[0m')

time.sleep(10)

break

def car(n):

while 1:

time.sleep(random.randrange(8))

if event.isSet(): # 判断标志位是否设定

print("car [%s] is running.." % n)

else:

print("car [%s] is waiting for the red light.." %n)

if __name__ == '__main__':

Light.start()

for i in range(3):

t.start()

import time

import random

def door():

count = 0

while True:

if door_event.is_set():

print("\033[32;1mdoor opening....\033[0m")

count +=1

else:

print("\033[31;1mdoor closed...., swipe to open.\033[0m")

count = 0 #清空计时器

door_event.wait()

if count > 3:#门开了已经3s了,该关了

door_event.clear()

time.sleep(0.5)

def staff(n):

print("staff [%s] is comming..." % n )

while True:

if door_event.is_set():

print("\033[34;1mdoor is opened, passing.....\033[0m")

break

else:

print("staff [%s] sees door got closed, swipping the card....." % n)

door_event.set()

print("door is opening...")

time.sleep(0.5)

if __name__ == "__main__":

for i in range(5):

time.sleep(random.randrange(3))

p.start()

1.   queue.Queue(maxsize=0)  先入先出

qsize()                                                 查询队列中数据的个数

put(item,block=Ture,timeout=None)    往队列中放入数据

get(block=True,timeout=None)            取出数据。当队列中没有数据的时候，get将会造成阻塞，直到队列中又存入数据为止。参数block=False不会阻塞，timeout=1表示只卡1s

empty()                                                当队列为空返回True

full()                                                     当队列已满返回True

def put():

#time.sleep(1) # 将执行此函数的线程滞后，更好地观摩多线程的运行效果

try:

for i in range(50):

cou = i

q.put(i + 1, block=False)

else:

print("存入了{0}个".format(cou+1))

except queue.Full:

print("队列已满，存入了{0}个".format(cou))

def get():

try:

for i in range(50):

print(q.get(block=False))

except queue.Empty:

print("队列已空，无法取出数据")

def qsize():

# time.sleep(1)

print("此时队列中个数:",q.qsize())

q = queue.Queue(5) # 队列最多同时容纳5个数据

put_thr.start()

qsi_thr.start()

get_thr.start()

Queue

2.  queue.LifoQueue(maxsize=0)  先入后出

3.   PriorityQueue()  存储数据时可设置优先级

import queue

'''

'''

q = queue.PriorityQueue() # 生成队列

q.put((5,"lwz"))

q.put((10,"alex"))

q.put((2,"chenronghua")) # 数字越小优先级越高

print(q.get())

print(q.get())

print(q.get())

PriorityQueue

import queue

import time

def Producer():

count = 0

while True:

count += 1

q.put("骨头{0}".format(count))

print("生产了骨头{0}".format(count))

time.sleep(1)

def Customer(name):

while 1:

print("{0}取到并且吃了{1}".format(name,q.get()))

time.sleep(0.1)

if __name__ == "__main__":

q = queue.Queue()

c1.start()

c2.start()

p.start()

python——线程与多线程进阶

python——线程与多线程基础

&lbrack;python&rsqb; 线程简介

1.无开发经验,初学python   如果你不会其他语言,python是你的第一门语言: A Byte of Python (简明python教程,这个有中文版简明 Python 教程)是非常好的入门 ...

PYTHON线程知识再研习A

*:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; } /* ...

Python中，添加写入数据到已经存在的Excel的xls文件，即打开excel文件，写入新数据

java基础知识汇总

1.     类的访问控制权限共有两种:public和默认.默认级别的类只能被同一个包中的类看到,包外不可见. 2.     类成员的访问权限共有四种:public,protected,private ...

【Netty】&lpar;4&rpar;—源码AbstractBootstrap

MyPython

160A

#include int main() { int n; int sum1=0, sum2=0, sum3=0; int x, y, z; scanf("%d ...

python 3&period;x 字典的11种方法

python 3.x 字典的11种方法2017年11月25日 01:02:11 Milton-Long 阅读数:535 标签: python python字典方法 更多个人分类: python-学习之 ...

VMWare Workstation使用总结几则&lbrack;转&rsqb;

VMWare Workstation使用总结几则   1.安装 使用GHOST盘安装时一定要注意,需要把空盘建立分区并设置为主分区 PQ的使用形式,进入PQ找到磁盘设置为启用 否则 启动后显示Boot ...

strops&lpar;&rpar;

• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
10-31 1648
01-04 333
01-18 7916
04-13 483
01-04 405
08-31 845
10-21 5039

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。