''' Created on Jun 17, 2013 @author: smp ''' #-*- coding:utf-8 -*- import threading import time counter = 0 mutex=threading.Lock() class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): global counter,mutex time.sleep(1); if mutex.acquire(): counter += 1 print "I am %s,set counter:%s" %(self.name,counter) mutex.release() if __name__=="__main__": for i in range(0,10): my_thread = MyThread() my_thread.start()
I am Thread-1,set counter:1 I am Thread-2,set counter:2 I am Thread-4,set counter:3 I am Thread-3,set counter:4 I am Thread-5,set counter:5 I am Thread-6,set counter:6 I am Thread-7,set counter:7 I am Thread-9,set counter:8 I am Thread-10,set counter:9 I am Thread-8,set counter:10