1.线程创建
1.1函数创建线程
def helloworld():
time.sleep(2)
print("hello world")
t = threading.Thread(target=helloworld)
t.start()
print("main thread")
1.2类创建线程
class HelloWorld(threading.Thread):
def __init__(self,id):
self.id = id
super(HelloWorld,self).__init__()
def run(self):
time.sleep(2)
print("thread %d helloworld" % self.id)
for i in range(5):
t = HelloWorld(i)
t.start()
print("main thread")
2.线程的方法
t.start() 启动线程活动
t.join() 保证当前线程执行完成以后,再执行其他线程。
import threading,time
count = 0
def adder():
global count
count = count + 1
time.sleep(0.1)
count = count + 1
threads = []
for i in range(100):
thread = threading.Thread(target=adder)
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
print(count)
3.线程锁
资源总是有限的,程序运行如果对同一个对象进行操作,则有可能造成资源的争用,甚至导致死锁 ,也可能导致读写混乱。
1.Lock.acquire([blocking])
2.Lock.release()
3.threading.Lock() 加载线程的锁对象,是一个基本的锁对象,一次只能一个锁定,其余锁请求,需等待锁释放后才能获取4.threading.RLock() 多重锁,在同一线程中可用被多次acquire。如果使用RLock,那么acquire和release必须成对出现, 调用了n次acquire锁请求,则必须调用n次的release才能在线程中释放锁对象。
函数加锁
import threading
import time
count = 0
def adder(addlock):
global count
addlock.acquire()
count = count +1
addlock.release()
time.sleep(0.1)
addlock.acquire()
count = count + 1
addlock.release()
addlock = threading.Lock()
threads = []
for i in range(100):
thread = threading.Thread(target=adder,args = (addlock,))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
print(count)
函数with加锁
import threading
import time
count = 0
def adder(addlock):
global count
with addlock:
count = count +1
time.sleep(0.1)
with addlock:
count = count + 1
addlock = threading.Lock()
threads = []
for i in range(100):
thread = threading.Thread(target=adder,args = (addlock,))
thread.start()
threads.append(thread)
for thread in threads:
thread.join()
print(count)
类wtih加锁:
import threading
import time
class HelloWorld(threading.Thread):
count =0
addlock = threading.Lock()
def run(self):
with HelloWorld.addlock:
HelloWorld.count +=1
time.sleep(0.5)
with HelloWorld.addlock:
HelloWorld.count += 1
threads = []
for i in range(5):
t = HelloWorld()
t.start()
threads.append(t)
for t in threads:
t.join()
print(HelloWorld.count)
python 信号量
同时访问5个线程。
import time
import threading
semaphore = threading.Semaphore(5) #添加一个计数器
def foo():
semaphore.acquire() #计数器获得锁
time.sleep(2) #程序休眠2秒
print("ok",time.ctime())
semaphore.release() #计数器释放锁
for i in range(20):
t1=threading.Thread(target=foo,args=()) #创建线程
t1.start() #启动线程
队列queue多应用在多线程应用中,多线程访问共享变量。对多线程而言,访问共享变量时,队列queue是线程安全的。
import threading
import queue
import time
numconsumers = 2
numprofucers = 2
nummessages = 4
lock = threading.Lock()
dataQueue = queue.Queue()
def producer(idnum):
for msgnum in range(nummessages):
dataQueue.put("producer id=%d,count=%d" % (idnum,msgnum))
def consumer(idnum):
while not dataQueue.empty():
data = dataQueue.get(block=False)
with lock:
print("consumer",idnum,"got =>",data)
time.sleep(0.1)
if __name__ == '__main__':
consumerThreads = []
producerThreads = []
for i in range(numprofucers):
t = threading.Thread(target = producer,args = (i,))
producerThreads.append(t)
t.start()
print(dataQueue.qsize())
for i in range(numconsumers):
t = threading.Thread(target=consumer,args =(i,))
consumerThreads.append(t)
t.start()
for t in producerThreads:
t.join()
for t in consumerThreads:
t.join()
python多线程 不合适cpu密集操作型的任务,适合io操作密集型任务。