threads blocked during import?

Geoff Talvola gtalvola at nameconnector.com
Tue Apr 10 15:24:05 EDT 2001


I was wondering the other day: if two threads try to import the same module 
at the same time, what happens?  I wrote a test program, and it looks like 
an import blocks all other threads from importing.  This is probably a good 
thing, since you only want the module to be imported once.

Here's the test program, and the helper module that it imports.  Running it 
on my WinNT box shows that the 2nd thread to try to import the module 
blocks while the first thread is importing it, and the module doesn't get 
imported twice.  That's a good thing.

My question for the gurus is, can I count on this locking taking place, and 
put code that absolutely needs to run only once at module level without any 
special locking?

###################################
######### test.py
import threading, time

def threadfunc():
     print 'threadfunc:', threading.currentThread().getName(), 'before 
importing slowimport'
     import slowimport
     print 'threadfunc:', threading.currentThread().getName(), 'after 
importing slowimport'
     for i in range(10):
         time.sleep(1.0)
         print 'threadfunc:', threading.currentThread().getName(), i

threads = []
for i in range(2):
     th = threading.Thread(None, threadfunc)
     th.start()
     threads.append(th)
     time.sleep(3)

for th in threads:
     th.join()
###################################


###################################
######### slowimport.py
import time, threading

for i in range(10):
     time.sleep(1.0)
     print 'slowimport:', threading.currentThread().getName(), i
###################################


--

- Geoff Talvola
   gtalvola at NameConnector.com




More information about the Python-list mailing list