學習Python5(Thread)

測試代碼

#coding:utf8
import thread, time, random

print '-'*25, '測試1', '-'*25
count = 0
lock = thread.allocate_lock()
def threadTest():
    global count, lock
    lock.acquire()
    for i in xrange(1000000):
        count += 1
    lock.release()
for i in range(5):
    thread.start_new_thread(threadTest, ()) #如果對start_new_thread函數不是很瞭解,不要着急,馬上就會講解
    # print thread.get_ident()
    # print thread.stack_size()
    time.sleep(0.1)
print count #count是多少呢?是10000 * 10 嗎?

# print '-'*25, '測試2', '-'*25
# def threadFunc(a = None, b = None, c = None, d = None):
#     print time.strftime('%H:%M:%S', time.localtime()), a
#     time.sleep(1)    
#     print time.strftime('%H:%M:%S', time.localtime()), b
#     time.sleep(1)
#     print time.strftime('%H:%M:%S', time.localtime()), c
#     time.sleep(1)
#     print time.strftime('%H:%M:%S', time.localtime()), d
#     time.sleep(1)
#     print time.strftime('%H:%M:%S', time.localtime()), 'over'

# thread.start_new_thread(threadFunc, (3, 4, 5, 6))   #創建線程,並執行threadFunc函數。
# time.sleep(5)

# print '-'*25, '測試3:', '-'*25
# thread.start_new_thread(lambda : (thread.interrupt_main(), ), ())
# try:
#     time.sleep(2)
# except KeyboardInterrupt, e:
#     print 'error:', e
# print 'over'

測試結果

------------------------- 測試1 -------------------------
5000000
>>> 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章