File: test__threadsafety.py

package info (click to toggle)
python-scipy 1.1.0-7
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 93,828 kB
  • sloc: python: 156,854; ansic: 82,925; fortran: 80,777; cpp: 7,505; makefile: 427; sh: 294
file content (53 lines) | stat: -rw-r--r-- 1,378 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from __future__ import division, print_function, absolute_import

import threading
import time
import traceback

from numpy.testing import assert_
from pytest import raises as assert_raises

from scipy._lib._threadsafety import ReentrancyLock, non_reentrant, ReentrancyError


def test_parallel_threads():
    # Check that ReentrancyLock serializes work in parallel threads.
    #
    # The test is not fully deterministic, and may succeed falsely if
    # the timings go wrong.

    lock = ReentrancyLock("failure")

    failflag = [False]
    exceptions_raised = []

    def worker(k):
        try:
            with lock:
                assert_(not failflag[0])
                failflag[0] = True
                time.sleep(0.1 * k)
                assert_(failflag[0])
                failflag[0] = False
        except:
            exceptions_raised.append(traceback.format_exc(2))

    threads = [threading.Thread(target=lambda k=k: worker(k))
               for k in range(3)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()

    exceptions_raised = "\n".join(exceptions_raised)
    assert_(not exceptions_raised, exceptions_raised)


def test_reentering():
    # Check that ReentrancyLock prevents re-entering from the same thread.

    @non_reentrant()
    def func(x):
        return func(x)

    assert_raises(ReentrancyError, func, 0)