threading

from time import ctime,sleep

def music(func):
for i in range(2):
print('我在听音乐 {0}. {1}'.format(func, ctime()))
sleep(3)

def movie(func):
for i in range(2):
print('我在看电影 {0}. {1}'.format(func, ctime()))
sleep(5)

if __name__ == '__main__':
music('夜空中最亮的星')
movie('英伦对决')

print('结束啦. {0}'.format(ctime()))

执行结果:

我在听音乐 夜空中最亮的星. Wed Dec 6 15:15:16 2017
我在听音乐 夜空中最亮的星. Wed Dec 6 15:15:19 2017
我在看电影 英伦对决. Wed Dec 6 15:15:22 2017
我在看电影 英伦对决. Wed Dec 6 15:15:27 2017
结束啦. Wed Dec 6 15:15:32 2017

 

#-*- coding: utf-8 -*-
from time import ctime,sleep
import threading

def music(func):
for i in range(2):
print('我在听音乐 {0}. {1}'.format(func, ctime()))
sleep(3)

def movie(func):
for i in range(2):
print('我在看电影 {0}. {1}'.format(func, ctime()))
sleep(5)

if __name__ == '__main__':
t1 = threading.Thread(target=music, args=('夜空中最亮的星',))
t2 = threading.Thread(target=movie, args=('英伦对决',))

t1.setDaemon(True)
t1.start()
t2.setDaemon(True)
t2.start()
print('结束啦. {0}'.format(ctime()))

执行结果:

我在听音乐 夜空中最亮的星. Wed Dec 6 15:21:34 2017
我在看电影 英伦对决. Wed Dec 6 15:21:34 2017
结束啦. Wed Dec 6 15:21:34 2017

从执行结果看, 子线程(music,moive)和主线程( print('结束啦. {0}'.format(ctime())) )都是同一时间启动,但由于主线程执行结束,所以导致主线程也终止,这些设置为Daemon线程也将自动被杀死。

 

调整程序:

if __name__ == '__main__':
t1 = threading.Thread(target=music, args=('夜空中最亮的星',))
t2 = threading.Thread(target=movie, args=('英伦对决',))

t1.setDaemon(True)
t1.start()
t2.setDaemon(True)
t2.start()

t1.join()
t2.join()
print('结束啦. {0}'.format(ctime()))

执行结果:

我在听音乐 夜空中最亮的星. Wed Dec 6 15:27:44 2017
我在看电影 英伦对决. Wed Dec 6 15:27:44 2017
我在听音乐 夜空中最亮的星. Wed Dec 6 15:27:47 2017
我在看电影 英伦对决. Wed Dec 6 15:27:49 2017
结束啦. Wed Dec 6 15:27:54 2017

加入了join()方法,用于等待线程终止,join()方法的作用是在子线程完成运行之前,这个子线程的父线程将一直被阻塞。

 

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

This constructor should always be called with keyword arguments. Arguments are:

group should be None; reserved for future extension when a ThreadGroup class is implemented.

target is the callable object to be invoked by the run() method. Defaults to None, meaning nothing is called.

name is the thread name. By default, a unique name is constructed of the form “Thread-N” where N is a small decimal number.

args is the argument tuple for the target invocation. Defaults to ().

kwargs is a dictionary of keyword arguments for the target invocation. Defaults to {}.

If not None, daemon explicitly sets whether the thread is daemonic. If None (the default), the daemonic property is inherited from the current thread.

If the subclass overrides the constructor, it must make sure to invoke the base class constructor (Thread.__init__()) before doing anything else to the thread.

Changed in version 3.3: Added the daemon argument.

 

线程锁(互斥锁Mutex):

#-*- coding: utf-8 -*-
import time
import threading

def addNum():
global num #在每个线程中获取这个全局变量
print('get num:', num)
num += 1 #对此公共变量进行+1操作

num = 0 #设定一个公共变量
thread_list = []

for x in range(100):
t = threading.Thread(target=addNum, args=())
t.start()
thread_list.append(t)

for t in thread_list: #等所有线程执行完毕
t.join()

print('final num:', num)

加锁:
#-*- coding: utf-8 -*-
import time
import threading

def addNum():
global num #在每个线程中获取这个全局变量
print('get num:', num)
lock.acquire() #修改数据前加锁
num += 1 #对此公共变量进行+1操作
lock.release() #修改数据后释放

num = 0 #设定一个公共变量
thread_list = []
lock = threading.Lock() #生成全局锁

for x in range(100):
t = threading.Thread(target=addNum, args=())
t.start()
thread_list.append(t)

for t in thread_list: #等所有线程执行完毕
t.join()

print('final num:', num)


semaphore(信号量):

互斥锁同时只允许一个线程更改数据,而semaphore是同时允许一定数量的线程更改数据。

 

import time
import threading

def run(n):
semaphore.acquire()
time.sleep(1)
print("run the thread: %s\n" % n)
semaphore.release()

if __name__ == "__main__":
thread_list = []
semaphore = threading.BoundedSemaphore(5)
for i in range(20):
t = threading.Thread(target=run, args=(i,))
t.start()
thread_list.append(t)

for x in thread_list:
x.join()
print("run over")

Timer objects:
import threading
def hello():
print("hello, world!")

t = threading.Timer(6, hello)
t.start()


queue object:
import threading
import queue
import time

def producer():
for i in range(10):
q.put('数字:{0}'.format(i))
print("生产数字:{0}".format(i))
time.sleep(0.5)

q.join()
print("所有数字已被取完~")

def consumer(n):
while True:
time.sleep(0.6)
print("{0} 取到".format(n), q.get())
q.task_done()
if q.empty(): break

q = queue.Queue()

t = threading.Thread(target=producer)
t.start()

c1 = consumer('jacky')

------------------------------------
import time
import random
import queue
import threading

q = queue.Queue()
def producer(name):
count = 0
while count < 20:
time.sleep(random.randrange(3))
q.put(count)
print('producer %s has produced %s bozi...'% (name, count))
count += 1

def consumer(name):
count = 0
while count < 20:
time.sleep(random.randrange(4))
if not q.empty():
data = q.get()
#print(data)
print('\033[32;1mconsumer %s has eat %s baozi...\033[0m'%(name, data))
else:
print("no baozi anymore")
count += 1

p1 = threading.Thread(target=producer, args=('A',))
c1 = threading.Thread(target=consumer, args=('B',))

p1.start()
c1.start()
posted @ 2017-12-21 15:40  helloworld899  阅读(195)  评论(0编辑  收藏  举报