python并发编程
2019-06-13 本文已影响0人
红色火苗
一:多线程
#!/usr/bin/env python
# -*- coding: utf_8 -*-
# 1.多线程
from __future__ import print_function
import time
import threading
def say_hi():
print('halo world')
def main():
for i in range(5):
thread = threading.Thread(target=say_hi)
thread.start()
if __name__ == '__main__':
stime = int(time.time())
main()
etime = int(time.time())
print('use-time',etime-stime)
二:多线程的并发运行
#!/usr/bin/env python
# -*- coding: utf_8 -*-
# 2.多线程
from __future__ import print_function
import time
import threading
def say_hi():
time.sleep(1)
print('halo world')
def main():
for i in range(5):
thread = threading.Thread(target=say_hi)
thread.start()
if __name__ == '__main__':
stime = int(time.time())
main()
etime = int(time.time())
print('use-time', etime - stime)
三:如何给线程传递参数?
#!/usr/bin/env python
# -*- coding: utf_8 -*-
# 3.多线程传递参数
from __future__ import print_function
import time
import threading
def say_hi(count,name):
while count > 0:
print(count,"hello",name)
count -= 1
def main():
usernames = ['jacke','bob','lucy','jone','mike']
for i in range(5):
thread = threading.Thread(target=say_hi,args=(50,usernames[i]))
thread.start()
if __name__ == '__main__':
stime = int(time.time())
main()
etime = int(time.time())
print('use-time', etime - stime)
四:通过继承创建线程
from __future__ import print_function
import threading
class MyThread (threading.Thread):
def __init__(self,count,name):
super(MyThread,self).__init__()
self.count = count
self.name = name
def run(self):
while self.count > 0:
print("hello",self.name)
self.count -= 1
def main():
usernames=['jacke','bob','lucy','joe','maike']
for i in range(5):
thread = MyThread(50,usernames[i])
thread.start()
if __name__ == '__main__':
main()
五:线程同步和互斥锁 保证线程的安全
# 5.线程同步和互斥锁
from __future__ import print_function
import threading
lock = threading.Lock()
num = 0
def incre(count):
global num
while count>0:
with lock:
num += 1
count -= 1
def main():
threads = []
for i in range(10):
thread = threading.Thread(target=incre,args=(100000,))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
print("expected value is",num)
if __name__ == '__main__':
main()
六:线程安全队列
# 先进先出 队列
from queue import Queue
q = Queue()
for i in range(10):
q.put(i)
while not q.empty():
print(q.get())
# 先进后出队列
from queue import LifoQueue
q = LifoQueue()
for i in range(10):
q.put(i)
while not q.empty():
print(q.get())
# 按指定优先级输出
from queue import PriorityQueue
class Job(object):
def __init__(self, priority, description):
self.priority = priority
self.description = description
print('New job:', description)
return
def __lt__(self, other):
return self.priority < other.priority
q = PriorityQueue()
q.put(Job(5, 'Mid-level job'))
q.put(Job(10, 'Low-level job'))
q.put(Job(1, 'Important job'))
while not q.empty():
next_job = q.get()
print('Processing job', next_job.description)
未完待续:
多进程
协程