import time as t
import threading
def fun():
print('start fun')
t.sleep(2)
print('end fun')
print('main thread')
## 注意:此处函数不带括号
t1 = threading.Thread(target=fun, args=())
t1.start()
t.sleep(1)
print('main thread end')
>main thread
start fun
main thread end
end fun
## 从结果看出:主程序结束后,线程并未结束
案例07:守护线程
import time
import threading
def fun():
print("Start fun")
time.sleep(2)
print("end fun")
print("Main thread")
t1 = threading.Thread(target=fun, args=() )
# 社会守护线程的方法,必须在start之前设置,否则无效
t1.setDaemon(True)
# 设置线程的第二种方式
#t1.daemon = True
t1.start()
time.sleep(1)
print("Main thread end")
>Main thread
Start fun
Main thread end
# 主线程结束后,守护线程也结束
import threading
import time
# 1. 类需要继承自threading.Thread
class MyThread(threading.Thread):
def __init__(self, arg):
super(MyThread, self).__init__()
self.arg = arg
# 2 必须重写run函数,run函数代表的是真正执行的功能
def run(self):
time.sleep(2)
print("The args for this class is {0}".format(self.arg))
for i in range(5):
t = MyThread(i)
t.start()
t.join()
print("Main thread is done!!!!!!!!")
>The args for this class is 0
The args for this class is 1
The args for this class is 2
The args for this class is 3
The args for this class is 4
Main thread is done!!!!!!!!
案例10:企业多线程写法
import threading
from time import sleep, ctime
class ThreadFunc:
def __init__(self, name):
self.name = name
def loop(self, nloop, nsec):
"""
:param nloop: loop函数的名称
:param nsec: 系统休眠时间
:return:
"""
print('Start loop ', nloop, 'at ', ctime())
sleep(nsec)
print('Done loop ', nloop, ' at ', ctime())
def main():
print("Starting at: ", ctime())
# 以下t1 和 t2的定义方式相等
t = ThreadFunc("loop")
t1 = threading.Thread(target=t.loop, args=("LOOP1", 4))
# 下面这种写法更西方人,工业化一点
t2 = threading.Thread(target=ThreadFunc('loop').loop, args=("LOOP2", 2))
t1.start()
t2.start()
t1.join()
t2.join()
print("ALL done at: ", ctime())
if __name__ == '__main__':
main()
>Starting at: Thu Aug 23 22:55:49 2018
Start loop LOOP1 at Thu Aug 23 22:55:49 2018
Start loop LOOP2 at Thu Aug 23 22:55:49 2018
Done loop LOOP2 at Thu Aug 23 22:55:51 2018
Done loop LOOP1 at Thu Aug 23 22:55:53 2018
ALL done at: Thu Aug 23 22:55:53 2018
2.7 共享变量
共享变量: 当多个现成同时访问一个变量的时候,会产生共享变量的问题
案例11:共享变量问题
import threading
sum = 0
n = 1000000
def Add():
global sum, n
for i in range(n):
sum += 1
def Minu():
global sum, n
for i in range(n):
sum -= 1
if __name__ == '__main__':
print('Starting......{0}'.format(sum))
t1 = threading.Thread(target=Add, args=())
t2 = threading.Thread(target=Minu, args=())
t1.start()
t2.start()
t1.join()
t2.join()
print('End......{0}'.format(sum))
>Starting......0
End......-182314
共享变量问题解决方法:锁(Lock)---是一个标志,表示一个线程在占用一些资源
案例12:上锁-->使用共享资源-->取消锁,释放锁
import threading
sum = 0
n = 1000000
lock =threading.Lock()
def Add():
global sum, n
for i in range(n):
## 上锁,申请锁
lock.acquire()
sum += 1
## 释放锁
lock.release()
def Minu():
global sum, n
for i in range(n):
lock.acquire()
sum -= 1
lock.release()
if __name__ == '__main__':
print('Starting......{0}'.format(sum))
t1 = threading.Thread(target=Add, args=())
t2 = threading.Thread(target=Minu, args=())
t1.start()
t2.start()
t1.join()
t2.join()
print('End......{0}'.format(sum))
>Starting......0
End......0
import threading
import time
# Python2
# from Queue import Queue
# Python3
import queue
class Producer(threading.Thread):
def run(self):
global queue
count = 0
while True:
# qsize返回queue内容长度
if queue.qsize() < 1000:
for i in range(100):
count = count +1
msg = '生成产品'+str(count)
# put是网queue中放入一个值
queue.put(msg)
print(msg)
time.sleep(0.5)
class Consumer(threading.Thread):
def run(self):
global queue
while True:
if queue.qsize() > 100:
for i in range(3):
# get是从queue中取出一个值
msg = self.name + '消费了 '+queue.get()
print(msg)
time.sleep(1)
if __name__ == '__main__':
queue = queue.Queue()
for i in range(500):
queue.put('初始产品'+str(i))
for i in range(2):
p = Producer()
p.start()
for i in range(5):
c = Consumer()
c.start()
import threading
import time
# 参数定义最多几个线程同时使用资源
semaphore = threading.Semaphore(3)
def func():
if semaphore.acquire():
print(threading.currentThread().getName() + ' get semaphore')
time.sleep(2)
semaphore.release()
print(threading.currentThread().getName() + ' release semaphore')
for i in range(8):
t1 = threading.Thread(target=func)
t1.start()
案例17:threading.Timer--利用多线程,在指定时间后启动一个功能
import threading
import time
def func():
print("I am running.........")
time.sleep(4)
print("I am done......")
if __name__ == "__main__":
t = threading.Timer(6, func)
t.start()
i = 0
while True:
print("{0}***************".format(i))
time.sleep(3)
i += 1
import threading
import time
class MyThread(threading.Thread):
## 重写run函数
def run(self):
global num
time.sleep(1)
if mutex.acquire(1):
num = num+1
msg = self.name+' set num to '+str(num)
print(msg)
mutex.acquire()
mutex.release()
mutex.release()
num = 0
## 实例化可重入锁
mutex = threading.RLock()
def testTh():
for i in range(5):
t = MyThread()
t.start()
import multiprocessing
from time import sleep, ctime
## interval 间隔
def clock(interval):
while True:
print("The time is %s" % ctime())
sleep(interval)
if __name__ == '__main__':
p = multiprocessing.Process(target=clock, args = (5,))
p.start()
while True:
print('sleeping.......')
sleep(1)
>略
通过加过可看出此时两个进程交替运行
案例20:派生子进程
import multiprocessing
from time import sleep, ctime
class ClockProcess(multiprocessing.Process):
def __init__(self, interval):
super().__init__()
self.interval = interval
def run(self):
while True:
print("The time is %s" % ctime())
sleep(self.interval)
if __name__ == '__main__':
p = ClockProcess(3)
p.start()
while True:
print('sleeping.......')
sleep(1)
>sleeping.......
The time is Sat Aug 25 14:55:23 2018
sleeping.......
sleeping.......
sleeping.......
The time is Sat Aug 25 14:55:26 2018
sleeping.......
sleeping.......
案例21:查看pid,ppid以及他们的关系
from multiprocessing import Process
import os
def info(title):
print(title)
print('module name:', __name__)
# 得到父亲进程的id
print('parent process:', os.getppid())
# 得到本身进程的id
print('process id:', os.getpid())
def f(name):
info('function f')
print('hello', name)
if __name__ == '__main__':
info('main line')
p = Process(target=f, args=('bob',))
p.start()
p.join()
>main line
module name: __main__
parent process: 4348
process id: 6500
function f
module name: __mp_main__
parent process: 6500
process id: 7340
hello bob
## 可知,两个进程共用父进程