python进阶笔记 thread 和 threading模块学习

Python通过两个标准库thread和threading提供对线程的支持。
thread提供了低级别的、原始的线程以及一个简单的锁。
threading基于Java的线程模型设计。
锁(Lock)和条件变量(Condition)在Java中是对象的基本行为(每一个对象都自带了锁和条件变量),而在Python中则是独立的对象。
start_new_thread()要求一定要有前两个参数。所以,就算我们想要运行的函数不要参数,我们也要传一个空的元组。

test_thread.py
#! /usr/bin/env python
# -*- coding:utf-8 -*-
import thread
import time
from time import sleep,ctime

test_list = [5,8]
def f1():
print 'start f1 at:',ctime()
sleep(5)
print 'f1 done at:',ctime()
def f2():
print 'start f1 at:',ctime()
sleep(3)
print 'f1 done at:',ctime()
def main():
print "start:",ctime()
thread.start_new_thread(f1,())
thread.start_new_thread(f2,())
sleep(6)
print "all end:",ctime()
if __name__ == '__main__':
main()

test_threading.py
#! /usr/bin/env python
# -*- coding:utf-8 -*-
import threading
import time

exitFlag = 0

class myThread(threading.Thread):
def __init__(self,threadID,name,delay):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.delay = delay
def run(self):
print "Starting" + self.name
print_time(self.name,self.delay,5)
print "Exiting" + self.name
def print_time(threadName,delay,counter):
while counter:
try:
if exitFlag:
thread.exit()
time.sleep(delay)
print "%s:%s" % (threadName, time.ctime(time.time()))
counter -= 1
except Exception,e:
logging.info(e)
thread1 = myThread(1,"Thread-1",1)
thread2 = myThread(2,"Thread-2",2)

thread1.start()
thread2.start()

print "Exiting Main Thread"

python多线程threading.Lock锁的用法

#创建锁
mutex = threading.Lock()
#锁定
mutex.acquire([timeout])
#释放
mutex.release()

test_threading_lock.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import threading
import time

class my_thread(threading.Thread):
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.release()
num = 0
mutex = threading.Lock()
def test():
for i in range(5):
t = my_thread()
t.start()
if __name__ == '__main__':
test()

python 多线程中常用到的几个方法,链接地址:http://blog.chinaunix.net/uid-27571599-id-3484048.html



 

你可能感兴趣的