一,在import thread之后,我们help(thread)一下,可以看到如下信息:
- NAME thread
- FILE (built-in)
- DESCRIPTION
- This module provides primitive operations to write multi-threaded programs.
- The 'threading' module provides a more convenient interface.
- CLASSES
- __builtin__.object
- lock
- exceptions.Exception(exceptions.BaseException)
- error
- FUNCTIONS
- ...
我们看到其并没有thread或相似的类,只包含了两个类lock&error以及一些方法。
现主要关注接口函数,暂时忽略其它:
①lock相关的函数说明:
分配一个锁:allocate_lock() -> lock object (allocate() is an obsolete synonym)
操作锁的方法:
acquire() -- lock the lock, possibly blocking until it can be obtained
release() -- unlock the lock
locked() -- test whether the lock is currently locked
/* Deadlocks may ensue. */由程序员来保证不死锁。
②线程相关的函数说明:
创建一个新线程:start_new_thread(function,args[,kwargs]) (start_new() is an obsolete synonym)
退出线程:exit()和exit_thread() (PyThread_exit_thread() is an obsolete synonym)
二,lock相关的函数使用示例(略去error):
- import thread
- def print_status(a_lock):
- if a_lock.locked():
- print "locked"
- else:
- print "not locked"
-
- a_lock = thread.allocate_lock()
- print_status(a_lock)
- a_lock.acquire()
- print_status(a_lock)
- a_lock.release()
- print_status(a_lock)
三,thread相关的函数使用示例:- import thread
- def run(n):
- # a back door, can not be run 4 times
- if n == 4:
- thread.exit()
- for i in range(n):
- print i
- thread.start_new_thread(run,(5,))
四,解决一个同步问题
试解决以下同步问题:使用两个线程交替输出“Hello”与“World”各5次,以“Hello”开始以“World”结束。
①HelloWorld问题的同步模型建立:
- semaphore h = 1, w = 0
- # because the semaphore w is 0,so we should acquire the lock w to let it be zero(locked) when we use python to .
- thread1()
- {
- while(true)
- {
- p(h)
- do something;
- v(w)
- }
- }
- thread2()
- {
- while(true)
- {
- p(w)
- do something;
- v(h)
- }
- }
②使用Python实现上述同步模型,两个解决方案如下。
方案A用main线程和另一个线程来交替打印。
方案B使用除main线程外的另两个线程交替打印“Hello”与“World"。
- import thread
- def world():
- for i in range(5):
- w_lock.acquire() # i want to print world
- print "world"
- h_lock.release() # you can print hello now
- w_lock.release()
- # main thread
- print "use two threads to print hello&world"
- h_lock = thread.allocate_lock()
- w_lock = thread.allocate_lock()
- w_lock.acquire(); # "print world" can not be started first
- thread.start_new_thread(world,())
- for i in range(5):
- h_lock.acquire()
- print "hello"
- w_lock.release()
- # raw_input("finished")
- import thread
- def hello():
- for i in range(5):
- h_ok.acquire()
- print "hello"
- w_ok.release()
- def world():
- for i in range(5):
- w_ok.acquire()
- print "world"
- h_ok.release()
- # main thread
- print "use two threads to print hello&world"
- h_ok = thread.allocate_lock()
- w_ok = thread.allocate_lock()
- w_ok.acquire()
- thread.start_new_thread(hello,())
- thread.start_new_thread(world,())
- raw_input("finished") # !!it is necessary,in case main thread exit too early
阅读(10108) | 评论(0) | 转发(0) |