一个进程中有很多线程,且线程共享所有进程中的资源。
多进程统统是去操作一个“东西”,可能会存在数据混乱的情况,例如:
1.示例一:
import threating loop = 10000 number = 0 def _add(cound): global number for i in range(count): number += 1 def _sub(count): global number for i in range(count): number -= 1 t1 = threading.Thread(target= _add,args= (loop,)) t2 = threading.Thread(target= _sub,args=(loop,)) t1.start() t2.start() t1.join() t2.join() t2执行完毕,才继续往下走
2.对线程进行加锁(当一个线程执行完成后会将锁释放,然后另一个线程申请到锁进行执行最后释放锁)
import threading lock_object = threading.RLock()#需要先创建锁 lonp = 100000 number = 0 def _add(count): lock_object.acquire() #加锁 global number for i in range(count): number += 1 lock_object.release()#释放锁 def _sub(count): lock_object.acquire() #申请锁(等待) global number for i in range(count): number -= 1 lock_object.release() #释放锁 t1 = threading.Thread(target = _add, args=(loop,)) t2 = threading.Thread(target=_sub, args=(loop,)) t1.start() t2.start() t1.join() #t1线程执行完毕后,才继续往后走 t2.join() #t2线程执行完毕后,才继续往后走
标签:count,threading,t2,number,t1,安全,线程 From: https://www.cnblogs.com/jxyl/p/16647923.html