Python advanced note thread and threading module learning, pythonthreading
Python supports threads through two standard libraries: thread and threading.
Thread provides a low-level, original thread, and a simple lock.
Threading is a Java-based thread model design.
Lock and Condition variables are the basic behavior of objects in Java (each object has a Lock and Condition variable), while in Python, they are independent objects.
Start_new_thread () must have the first two parameters. Therefore, even if the function we want to run is not a parameter, we need to pass an empty tuples.
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 t 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"
Usage of python multi-thread threading. Lock
# Create a lock
Mutex = threading. Lock ()
# Locking
Mutex. acquire ([timeout])
# Release
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 multithreading commonly used several methods, link address: http://blog.chinaunix.net/uid-27571599-id-3484048.html