我是python的新手,並嘗試理解python中多線程的概念。根據我在Unix多線程編程方面的知識,如果main函數正在終止,那麼由main函數創建的線程也將被終止,而不管他們在線程中所做的工作(如果我們不使用任何pthread_join()函數) 。Python中多線程的意外行爲
但在python中通過多線程時,我沒有看到這個功能。即使我的主線程完成其工作,我的線程仍然運行成功。 所以我想知道,Python和Unix中的線程行爲不同......或者我錯過了一些東西。請幫助理解python中的這個線程特性。這裏是我在python中使用的代碼。
#! /usr/bin/python
import logging
import random
import threading
import time
logging.basicConfig(level=logging.DEBUG,
format='(%(threadName)-10s) %(message)s',
)
class Counter(object):
def __init__(self, start=0):
self.lock = threading.Lock()
self.value = start
def increment(self):
logging.debug('Waiting for lock')
# Getting the Lock
self.lock.acquire()
try:
logging.debug('Acquired lock')
self.value = self.value + 1
finally:
# Releasing the Lock
self.lock.release()
def worker(c):
for i in range(2):
pause = 4
logging.debug('Sleeping for %0.02f', pause)
time.sleep(pause)
c.increment()
logging.debug('Done')
if __name__ == '__main__':
counter = Counter()
for i in range(2):
t = threading.Thread(target=worker, args=(counter,))
t.start()
logging.debug('Counter: %d', counter.value)
那麼......你的問題是什麼?這非常含糊。你已經描述了功能,但這裏沒有真正的問題。 –