一般创建threading.Thread的子类来包装一个线程对象
import threading
import time
class timer(threading.thread):
def __init__(self,num,interval):
thredaing.thread__init__(self)
self.thread_num = num
self.interval = interval
self.thread_stop = False
def run(self):
while not self.thread_stop:
print "Thread:%d, Time: %s\n" %(self.thread_num, time.ctime())
time.sleep(self.interval)
def stop(self):
self.thread_stop = True
def test():
thread1 = timer(1,1)
thread1 = timer(2,2)
thread1.start()
thread2.start()
time.sleep(10)
thread1.stop()
thread2.stop()
return
if __name__=='__main__':
test()
线程安全的问题:
如果你的代码所在的进程中有多个线程在同时运行,而这些线程可能会同时运行这段代码。如果每次运行结果和单线程运行的结果是一样的,而且其他的变量的值也和预期的是一样的,就是线程安全的。或者说:一个类或者程序所提供的接口对于线程来说是原子操作或者多个线程之间的切换不会导致该接口的执行结果存在二义性,也就是说我们不用考虑同步的问题。
若有多个线程同时执行写操作,一般都需要考虑线程同步,否则就可能影响线程安全。
Queue模块实现了一个支持多producer和多consumer的FIFO队列。当共享信息需要安全的在多线程之间交换时,Queue非常有用。
import random
import threading
import time
from Queue import Queue
class Producer(threading.Thread):
def __init__(self, t_name, queue):
threading.Thread.__init__(self, name=t_name)
self.data=queue
def run(self):
for i in range(5):
print "%s: %s is producing %d to the queue!\n" %(time.ctime(), self.getName(), i)
self.data.put(i)
time.sleep(random.randrange(10)/5)
print "%s: %s finished!" %(time.ctime(), self.getName())
class Consumer(threading.Thread):
def __init__(self, t_name, queue):
threading.Thread.__init__(self, name=t_name)
self.data=queue
def run(self):
for i in range(5):
val = self.data.get()
print "%s: %s is consuming. %d in the queue is consumed!\n" %(time.ctime(), self.getName(), val)
time.sleep(random.randrange(10))
print "%s: %s finished!" %(time.ctime(), self.getName())
def main():
queue = Queue()
producer = Producer('Pro.', queue)
consumer = Consumer('Con.', queue)
producer.start()
consumer.start()
producer.join()
consumer.join()
print 'All threads terminate!'
if __name__ == '__main__':
main()
put( item[, block[, timeout]])
Queue的put方法是从队尾加入数据,如果可选参数block为true,线程被block,直到队列空出一个数据单元。反之,如果block参数为false,item被立即加入到空闲数据单元中,如果没有空闲数据单元,Full exception被抛出。
get( item[, block[, timeout]])