Module EDThreading
[hide private]
[frames] | no frames]

Source Code for Module EDThreading

 1  # -*- coding: utf8 -*- 
 2  # 
 3  #    Project: The EDNA Kernel 
 4  #             http://www.edna-site.org 
 5  # 
 6  #    File: "$Id:$" 
 7  # 
 8  #    Copyright (C) 2012-2012 European Synchrotron Radiation Facility 
 9  #                            Grenoble, France 
10  # 
11  #    Principal authors: Jérôme Kieffer (jerome.kieffer@esrf.fr) 
12  #  
13  # 
14  #    This program is free software: you can redistribute it and/or modify 
15  #    it under the terms of the GNU Lesser General Public License as published 
16  #    by the Free Software Foundation, either version 3 of the License, or 
17  #    (at your option) any later version. 
18  # 
19  #    This program is distributed in the hope that it will be useful, 
20  #    but WITHOUT ANY WARRANTY; without even the implied warranty of 
21  #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
22  #    GNU Lesser General Public License for more details. 
23  # 
24  #    You should have received a copy of the GNU General Public License 
25  #    and the GNU Lesser General Public License  along with this program.   
26  #    If not, see <http://www.gnu.org/licenses/>. 
27  # 
28   
29  """ 
30  Set an environment variable "EDNA_LOCK" to help debugging  
31  any dead-locks- inside EDNA  
32  """ 
33   
34  __authors__ = [ "Jérôme Kieffer" ] 
35  __contact__ = "jerome.kieffer@esrf.fr" 
36  __license__ = "LGPLv3+" 
37  __copyright__ = "European Synchrotron Radiation Facility, Grenoble, France" 
38  __date__ = "20120401" 
39  import uuid, sys, os, traceback 
40  import threading 
41  _Semaphore = threading._Semaphore 
42   
43  if os.environ.get("EDNA_LOCK", False): 
44 - class Semaphore(_Semaphore):
45 """ 46 threading.Semaphore like class with helper for fighting dead-locks 47 """
48 - def __init__(self, *arg, **kwarg):
49 _Semaphore.__init__(self, *arg, **kwarg) 50 self.blocked = []
51
52 - def acquire(self, *arg, **kwarg):
53 if self._Semaphore__value == 0: 54 uid = uuid.uuid4() 55 self.blocked.append(uid) 56 sys.stderr.write("Blocking sem %s" % 57 os.linesep.join([str(uid)] + \ 58 traceback.format_stack()[:-1] + [""])) 59 return _Semaphore.acquire(self, *arg, **kwarg)
60
61 - def release(self, *arg, **kwarg):
62 if self.blocked: 63 try: 64 uid = self.blocked.pop() 65 except Exception: 66 pass 67 else: 68 sys.stderr.write("Released sem %s %s" % (uid, os.linesep)) 69 _Semaphore.release(self, *arg, **kwarg)
70
71 - def __enter__(self):
72 self.acquire() 73 return self
74
75 - def __exit__(self, *arg, **kwarg):
76 self.release()
77 else: 78 Semaphore = threading.Semaphore 79