Debian Codegraph @

django/contrib/gis/geos/prototypes/threadsafe.py

raw
1 import threading
2
3 from django.contrib.gis.geos.base import GEOSBase
4 from django.contrib.gis.geos.libgeos import CONTEXT_PTR, error_h, lgeos, notice_h
5
6
7 class GEOSContextHandle(GEOSBase):
8 """Represent a GEOS context handle."""
9
10 ptr_type = CONTEXT_PTR
11 destructor = lgeos.finishGEOS_r
12
13 def __init__(self):
14 # Initializing the context handler for this thread with
15 # the notice and error handler.
16 self.ptr = lgeos.initGEOS_r(notice_h, error_h)
17
18
19 # Defining a thread-local object and creating an instance
20 # to hold a reference to GEOSContextHandle for this thread.
21 class GEOSContext(threading.local):
22 handle = None
23
24
25 thread_context = GEOSContext()
26
27
28 class GEOSFunc:
29 """
30 Serve as a wrapper for GEOS C Functions. Use thread-safe function
31 variants when available.
32 """
33
34 def __init__(self, func_name):
35 # GEOS thread-safe function signatures end with '_r' and take an
36 # additional context handle parameter.
37 self.cfunc = getattr(lgeos, func_name + "_r")
38 # Create a reference to thread_context so it's not garbage-collected
39 # before an attempt to call this object.
40 self.thread_context = thread_context
41
42 def __call__(self, *args):
43 # Create a context handle if one doesn't exist for this thread.
44 self.thread_context.handle = self.thread_context.handle or GEOSContextHandle()
45 # Call the threaded GEOS routine with the pointer of the context handle
46 # as the first argument.
47 return self.cfunc(self.thread_context.handle.ptr, *args)
48
49 def __str__(self):
50 return self.cfunc.__name__
51
52 # argtypes property
53 def _get_argtypes(self):
54 return self.cfunc.argtypes
55
56 def _set_argtypes(self, argtypes):
57 self.cfunc.argtypes = [CONTEXT_PTR, *argtypes]
58
59 argtypes = property(_get_argtypes, _set_argtypes)
60
61 # restype property
62 def _get_restype(self):
63 return self.cfunc.restype
64
65 def _set_restype(self, restype):
66 self.cfunc.restype = restype
67
68 restype = property(_get_restype, _set_restype)
69
70 # errcheck property
71 def _get_errcheck(self):
72 return self.cfunc.errcheck
73
74 def _set_errcheck(self, errcheck):
75 self.cfunc.errcheck = errcheck
76
77 errcheck = property(_get_errcheck, _set_errcheck)