Ho scritto un semplice programma di test utilizzando i blocchi di thread. Questo programma non si comporta come previsto e l'interprete python non si lamenta.Comportamento imprevisto quando si utilizzano i blocchi di thread python e le importazioni di circulair
test1.py:
from __future__ import with_statement
from threading import Thread, RLock
import time
import test2
lock = RLock()
class Test1(object):
def __init__(self):
print("Start Test1")
self.test2 = test2.Test2()
self.__Thread = Thread(target=self.myThread, name="thread")
self.__Thread.daemon = True
self.__Thread.start()
self.test1Method()
def test1Method(self):
print("start test1Method")
with lock:
print("entered test1Method")
time.sleep(5)
print("end test1Method")
def myThread(self):
self.test2.test2Method()
if __name__ == "__main__":
client = Test1()
raw_input()
test2.py:
from __future__ import with_statement
import time
import test1
lock = test1.lock
class Test2(object):
def __init__(self):
print("Start Test2")
def test2Method(self):
print("start test2Method")
with lock:
print("entered test2Method")
time.sleep(5)
print("end test2Method")
Entrambi i posti letto vengono eseguiti allo stesso tempo! Non è quello che mi aspettavo quando usavo il lucchetto.
Quando test2Method viene spostato su test1.py, tutto funziona correttamente. Quando creo il blocco in test2.py e lo importa in test1.py, tutto funziona correttamente. Quando creo il blocco in un file sorgente separato e lo importa sia in test1.py che in test2.py, tutto funziona correttamente.
Probabilmente ha a che fare con le importazioni della circonvallazione.
Ma perché Python non si lamenta di questo?
Grazie per la spiegazione. Python è abbastanza nuovo per me, non ho mai incontrato questo comportamento. Sono contento di averlo chiesto, perché potrebbe verificarsi anche in altre situazioni non thread. – user1997293
@ user1997293: Sì, hai ragione, questo comportamento è molto comune e felice che la mia risposta sia stata utile :) – mouad