1 import random
2 from math import sqrt
3 from os import getpid
4 from time import sleep, strftime
5 from threading import currentThread
6 from itertools import count, ifilter
7
8 import papyros
9
10
12 print '%s PID=%d/%s:\t%s' % (strftime('%H:%M:%S'), getpid(),
13 currentThread().getName(), msg)
14
15
17 '''A non-CPU-intensive job: sleep for a few seconds and return the sqrt of
18 a number.
19 '''
20
22 return 'SlowSqrt(%s)' % self.args[0]
23
25 t = random.randrange(1,5)
26 log('Pretending to work hard on computing sqrt(%s) for %d seconds' % (n,t))
27 sleep(t)
28 return sqrt(n)
29
30
32 '''A CPU intensive job: compute the prime factors of a number.'''
33
35 return 'PrimeFactors(%s)' % self.args[0]
36
38 log('Factorizing %s' % n)
39 factors = []
40 nextprime = sieve().next
41 candidate = nextprime()
42 thresh = sqrt(n)
43 while True:
44 if candidate > thresh:
45 factors.append(n)
46 break
47 d,m = divmod(n, candidate)
48 if m == 0:
49 factors.append(candidate)
50 n = d; thresh = sqrt(n)
51 else:
52 candidate = nextprime()
53 return factors
54
55
57
58
59 seq = count(2)
60 while True:
61 p = seq.next()
62 seq = ifilter(p.__rmod__, seq)
63 yield p
64