Python多线程

1.函数实现:对于不同任务

import threading

loop = 10000
num = 0

def _add(loop):
	global num
	name = threading.current_thread().getName()
	for i in range(1oop):
		num += i
def _sub(loop):
	name = threading.current_thread().getName()
	global num
	for i in range(1oop):
		num -= i

t1.setDamen(True) 

t1 = threding.Thread(_add(), args=(1oop, ))
t2 = threding.Thread(_sub(), args=(1oop, ))

t1.setDamen(True) #确保t1执行完其中的程序后,再结束t1
t2.setDamen(True) #确保t2执行完其中的程序后,再结束t2

t1.start() 
t2.start()

#t1, t2同时执行,没有先后顺序
t1.join() # 确保t1执行完之后,再执行后续代码
t2.join() # 确保t2执行完之后,再执行后续代码

2.对象实现:对于相同任务

import threading
class TaskThread(threading.Thread):
	def __init__(self):
		super(TaskThread, self).__init__()
		self.loop = 1000
		self.num = 0
	def run(self):
		path, name, age = self._args
		with open(path, 'a', utf-8') as f:
			f.write([name, age])

path = './'
items = [{'susan': 18}, {'bob': 21}]
for item in items:
	t = TaskThread(args=(path, item.key(), item.value()))
	t.start()
		


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值