[Patches] [Patch #103028] Make tempfile.mktemp threadsafe

noreply@sourceforge.net noreply@sourceforge.net
Thu, 28 Dec 2000 06:52:13 -0800


Patch #103028 has been updated. 

Project: python
Category: library
Status: Open
Submitted by: nobody
Assigned to : tim_one
Summary: Make tempfile.mktemp threadsafe

Follow-Ups:

Date: 2000-Dec-28 06:52
By: gvanrossum

Comment:
Randomly assigned to Tim.  I'd like mktemp to be thread-safe but I wish it
wouldn't have to use a lock. Is there any other way?

-------------------------------------------------------

Date: 2000-Dec-27 17:19
By: tseaver

Comment:
Doesn't need the 'global counter' in mktemp:

[/usr/lib/python1.5] $ diff -u tempfile.py.org tempfile.py
--- tempfile.py.org     Wed Dec 27 19:44:29 2000
+++ tempfile.py Wed Dec 27 20:05:57 2000
@@ -84,15 +84,35 @@
 
 counter = 0
 
+#
+#   In threaded Pythons, make this operation threadsafe.
+#
+try:
+    from threading import Lock
+    counterLock = Lock()
+except:
+    def _bumpCounter():
+        global counter
+        counter = counter + 1
+        return counter
+else:
+    def _bumpCounter():
+        global counter, counterLock
+        counterLock.acquire()
+        try:
+            counter = counter + 1
+            return counter
+        finally:
+            counterLock.release()
+
 
 # User-callable function to return a unique temporary file name
 
 def mktemp(suffix=""):
-    global counter
     dir = gettempdir()
     pre = gettempprefix()
     while 1:
-        counter = counter + 1
+        counter = _bumpCounter()
         file = os.path.join(dir, pre + `counter` + suffix)
         if not os.path.exists(file):
             return file

-------------------------------------------------------

-------------------------------------------------------
For more info, visit:

http://sourceforge.net/patch/?func=detailpatch&patch_id=103028&group_id=5470