Debian Codegraph @

pypy/module/cpyext/test/test_thread.py

raw symbols SCIP
1 import sys
2
3 import pytest
4
5 from pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase
6
7 only_pypy ="config.option.runappdirect and '__pypy__' not in sys.builtin_module_names"
8
9 class AppTestThread(AppTestCpythonExtensionBase):
10 @pytest.mark.skipif(only_pypy, reason='pypy only test')
11 @pytest.mark.xfail(reason='segfaults', run=False)
12 def test_get_thread_ident(self):
13 module = self.import_extension('foo', [
14 ("get_thread_ident", "METH_NOARGS",
15 """
16 #ifndef PyThread_get_thread_ident
17 #error "seems we are not accessing PyPy's functions"
18 #endif
19 return PyLong_FromLong(PyThread_get_thread_ident());
20 """),
21 ])
22 import threading
23 results = []
24 def some_thread():
25 res = module.get_thread_ident()
26 results.append((res, threading.get_ident()))
27
28 some_thread()
29 assert results[0][0] == results[0][1]
30
31 th = threading.Thread(target=some_thread, args=())
32 th.start()
33 th.join()
34 assert results[1][0] == results[1][1]
35
36 assert results[0][0] != results[1][0]
37
38 @pytest.mark.skipif(only_pypy, reason='pypy only test')
39 def test_acquire_lock(self):
40 module = self.import_extension('foo', [
41 ("test_acquire_lock", "METH_NOARGS",
42 """
43 #ifndef PyThread_allocate_lock
44 #error "seems we are not accessing PyPy's functions"
45 #endif
46 PyThread_type_lock lock = PyThread_allocate_lock();
47 if (PyThread_acquire_lock(lock, 1) != 1) {
48 PyErr_SetString(PyExc_AssertionError, "first acquire");
49 return NULL;
50 }
51 if (PyThread_acquire_lock(lock, 0) != 0) {
52 PyErr_SetString(PyExc_AssertionError, "second acquire");
53 return NULL;
54 }
55 PyThread_free_lock(lock);
56
57 Py_RETURN_NONE;
58 """),
59 ])
60 module.test_acquire_lock()
61
62 @pytest.mark.skipif(only_pypy, reason='pypy only test')
63 def test_release_lock(self):
64 module = self.import_extension('foo', [
65 ("test_release_lock", "METH_NOARGS",
66 """
67 #ifndef PyThread_release_lock
68 #error "seems we are not accessing PyPy's functions"
69 #endif
70 PyThread_type_lock lock = PyThread_allocate_lock();
71 PyThread_acquire_lock(lock, 1);
72 PyThread_release_lock(lock);
73 if (PyThread_acquire_lock(lock, 0) != 1) {
74 PyErr_SetString(PyExc_AssertionError, "first acquire");
75 return NULL;
76 }
77 PyThread_free_lock(lock);
78
79 Py_RETURN_NONE;
80 """),
81 ])
82 module.test_release_lock()
83
84 @pytest.mark.skipif(only_pypy, reason='pypy only test')
85 def test_timed_lock(self):
86 module = self.import_extension('foo', [
87 ("timed_acquire_lock", "METH_O",
88 """
89 #ifndef PyThread_acquire_lock_timed
90 #error "seems we are not accessing PyPy's functions"
91 #endif
92 PyLockStatus acquire_result;
93 int microseconds = PyLong_AsLong(args);
94 Py_BEGIN_ALLOW_THREADS
95 acquire_result = PyThread_acquire_lock_timed(global_lock, microseconds, 0);
96 Py_END_ALLOW_THREADS
97 if (acquire_result == PY_LOCK_ACQUIRED) {
98 Py_RETURN_TRUE;
99 } else {
100 Py_RETURN_FALSE;
101 }
102 """),
103 ("release_lock", "METH_NOARGS",
104 """
105 PyThread_release_lock(global_lock);
106 Py_RETURN_NONE;
107 """),
108 ("cleanup_lock", "METH_NOARGS",
109 """
110 // cleanup isn't part of the test, but I'd feel guilty otherwise
111 PyThread_free_lock(global_lock); global_lock=NULL;
112 Py_RETURN_NONE;
113 """
114 )
115 ],
116 prologue="static PyThread_type_lock global_lock;",
117 more_init="global_lock = PyThread_allocate_lock();"
118 )
119 try:
120 import threading
121 import time
122 failure = []
123 assert module.timed_acquire_lock(-1)
124 main_thread_should_release_the_lock_barrier = threading.Barrier(2)
125
126 def thread_func():
127 try:
128 if module.timed_acquire_lock(0):
129 failure.append("Lock should be held elsewhere")
130 return
131 if module.timed_acquire_lock(1):
132 failure.append("Lock should be held elsewhere")
133 return
134 finally:
135 main_thread_should_release_the_lock_barrier.wait()
136 if not module.timed_acquire_lock(1000000):
137 failure.append("Lock should have become available")
138 return
139 module.release_lock()
140 thread = threading.Thread(target=thread_func)
141 thread.start()
142 main_thread_should_release_the_lock_barrier.wait()
143 # At this point, thread_func should be waiting 1s for the lock,
144 # so sleep a short amount of time then let it have the lock.
145 time.sleep(0.01)
146 module.release_lock()
147
148 thread.join()
149 assert not failure, failure
150 finally:
151 module.cleanup_lock()
152
153 # The intr_flag isn't tested here though
154
155 @pytest.mark.skipif(only_pypy, reason='pypy only test')
156 @pytest.mark.xfail(reason='segfaults', run=False)
157 def test_tls(self):
158 module = self.import_extension('foo', [
159 ("create_key", "METH_NOARGS",
160 """
161 return PyLong_FromLong(PyThread_create_key());
162 """),
163 ("test_key", "METH_O",
164 """
165 int key = PyLong_AsLong(args);
166 if (PyThread_get_key_value(key) != NULL) {
167 PyErr_SetNone(PyExc_ValueError);
168 return NULL;
169 }
170 if (PyThread_set_key_value(key, (void*)123) < 0) {
171 PyErr_SetNone(PyExc_ValueError);
172 return NULL;
173 }
174 if (PyThread_get_key_value(key) != (void*)123) {
175 PyErr_SetNone(PyExc_ValueError);
176 return NULL;
177 }
178 Py_RETURN_NONE;
179 """),
180 ])
181 key = module.create_key()
182 assert key > 0
183 # Test value in main thread.
184 module.test_key(key)
185 raises(ValueError, module.test_key, key)
186 # Same test, in another thread.
187 result = []
188 import _thread, time
189 def in_thread():
190 try:
191 module.test_key(key)
192 raises(ValueError, module.test_key, key)
193 except Exception as e:
194 result.append(e)
195 else:
196 result.append(True)
197 _thread.start_new_thread(in_thread, ())
198 while not result:
199 print(".")
200 time.sleep(.5)
201 assert result == [True]
202
203 def test_tss(self):
204 module = self.import_extension('foo', [
205 ("tss", "METH_NOARGS",
206 """
207 void *tss_key = NULL;
208 /* non-Py_LIMITED_API */
209 Py_tss_t _tss_key = Py_tss_NEEDS_INIT;
210 int the_value = 1;
211 if ( PyThread_tss_is_created(&_tss_key) ) {
212 PyErr_SetString(PyExc_AssertionError,
213 "tss_is_created should not succeed yet");
214 return NULL;
215 }
216 /* This should be a no-op */
217 PyThread_tss_delete(&_tss_key);
218 /* Py_LIMITED_API */
219 tss_key = PyThread_tss_alloc();
220 if ( PyThread_tss_is_created(tss_key) ) {
221 PyErr_SetString(PyExc_AssertionError,
222 "tss_is_created should not succeed yet");
223 return NULL;
224 }
225 if (PyThread_tss_create(tss_key)) {
226 return NULL;
227 }
228 if (! PyThread_tss_is_created(tss_key)) {
229 return NULL;
230 }
231 /* Be sure additional calls succeed */
232 if (PyThread_tss_create(tss_key)) {
233 return NULL;
234 }
235 if (PyThread_tss_get(tss_key) != NULL) {
236 PyErr_SetString(PyExc_AssertionError,
237 "tss_get should not succeed yet");
238 return NULL;
239 }
240
241 if (PyThread_tss_set(tss_key, (void *)&the_value)) {
242 PyErr_SetString(PyExc_AssertionError,
243 "tss_set failed");
244 return NULL;
245 }
246 void *val = PyThread_tss_get(tss_key);
247 if (val == NULL) {
248 PyErr_SetString(PyExc_AssertionError,
249 "tss_get failed");
250 return NULL;
251 }
252 if (the_value != *(int*)val) {
253 PyErr_SetString(PyExc_AssertionError,
254 "retrieved value is wrong");
255 return NULL;
256 }
257 PyThread_tss_free(tss_key);
258 Py_RETURN_NONE;
259 """),
260 ])
261 module.tss()