summaryrefslogtreecommitdiff
path: root/modules/language/python/module/threading.scm
blob: 1f1f83b6318ae53ecb538fb0078be829d13971d4 (about) (plain)
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
54
55
56
57
(define-module (language python module threading)
  #:use-module (ice-9 threads)
  #:use-module (oop pf-objects)
  #:use-module (language python def)
  #:use-module (language python exceptions)
  #:use-module (language python list)
  #:export (RLock start_new_thread allocate_lock Thread))

(define-python-class RLock ()
  (define __init__
    (lambda (self)
      (set self '_lock (make-mutex 'recursive))))
  
  (define __enter__
    (lambda (self)
      (lock-mutex (ref self '_lock))))

  (define __leave__
    (lambda (self)
      (unlock-mutex (ref self '_lock))))

  (define acquire
    (lam (self (= blocking #t) (= timeout -1))
	 (if blocking
	     (if (< timeout 0)
		 (lock-mutex (ref self '_lock))
		 (let* ((cur (gettimeofday))
			(x   (+ (car cur) (/ (cdr cur) 1000000.0)))
			(y   (+ x timeout))
			(s   (floor y))
			(us  (floor (* (- y s) 1000000))))
		   (lock-mutex (ref self '_lock) (cons s us))))
	     (try-mutex (ref self '_lock)))))
  
  (define release __leave__))
    
(define allocate_lock
  (lambda () (RLock)))

(define (start_new_thread fkn args)
  (call-with-new-thread
   (lambda ()
     (apply fkn (to-list args)))))

(define-python-class Thread ()
  (define __init__
    (lam (self (= target None) (= args '()))
         (set self 'target target)
         (set self 'args   args)))

  (define start
    (lambda (self)
      (call-with-new-thread
       (lambda ()
         (apply (ref self 'target)
                (to-list (ref self 'args))))))))