Python threads and os.chdir
By Maxime Biais, Tuesday 23 January 2007 at 21:20 :: Python :: #19 :: rss
I had some problem using os.chdir and threads. In fact, current directory is shared between threads. Here is a simple python snippets to demonstrate it.
from threading import Thread import os import time class ThreadTest(Thread): def __init__(self): Thread.__init__(self) def run(self): for i in range(2): time.sleep(1) print "name=%s, cwd=%s" % (self.getName(), os.getcwd()) os.chdir("..") t1 = ThreadTest() t2 = ThreadTest() t1.start() # start first time.sleep(0.5) # .5 second shift t2.start()
outputs:
name=Thread-1, cwd=/home/max/work/blogcode name=Thread-2, cwd=/home/max/work name=Thread-1, cwd=/home/max name=Thread-2, cwd=/home
If chdir wasn't shared between threads, we could expect this:
name=Thread-1, cwd=/home/max/work/blogcode name=Thread-2, cwd=/home/max/work/blogcode name=Thread-1, cwd=/home/max name=Thread-2, cwd=/home/max
In a multi threaded program, try to avoid os.chdir, but if you really need to change current directory to run external program or whatever, use locks, . It depends why you need threads, but you may want to fork instead. Current directory is process dependant. Same program as above using fork:
import os import time def run(t, name): for i in range(2): time.sleep(t) print "name=%s, cwd=%s" % (name, os.getcwd()) os.chdir("..") pid = os.fork() if pid == 0: run(0.5, "father") else: run(0.5, "child-" + str(pid))
outputs:
name=father, cwd=/home/max/work/blogcode name=child-635, cwd=/home/max/work/blogcode name=father, cwd=/home/max/work name=child-635, cwd=/home/max/work
That's what we expected first when we write the threaded version. For more informations about fork, check the standard library: Process Management.



Comments
No comment.
Write your comment