parallel.py 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # https://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Functions for parallel computation on multiple cores.
  17. Introduced in Python-RSA 3.1.
  18. .. note::
  19. Requires Python 2.6 or newer.
  20. """
  21. from __future__ import print_function
  22. import multiprocessing as mp
  23. import rsa.prime
  24. import rsa.randnum
  25. def _find_prime(nbits, pipe):
  26. while True:
  27. integer = rsa.randnum.read_random_odd_int(nbits)
  28. # Test for primeness
  29. if rsa.prime.is_prime(integer):
  30. pipe.send(integer)
  31. return
  32. def getprime(nbits, poolsize):
  33. """Returns a prime number that can be stored in 'nbits' bits.
  34. Works in multiple threads at the same time.
  35. >>> p = getprime(128, 3)
  36. >>> rsa.prime.is_prime(p-1)
  37. False
  38. >>> rsa.prime.is_prime(p)
  39. True
  40. >>> rsa.prime.is_prime(p+1)
  41. False
  42. >>> from rsa import common
  43. >>> common.bit_size(p) == 128
  44. True
  45. """
  46. (pipe_recv, pipe_send) = mp.Pipe(duplex=False)
  47. # Create processes
  48. try:
  49. procs = [mp.Process(target=_find_prime, args=(nbits, pipe_send))
  50. for _ in range(poolsize)]
  51. # Start processes
  52. for p in procs:
  53. p.start()
  54. result = pipe_recv.recv()
  55. finally:
  56. pipe_recv.close()
  57. pipe_send.close()
  58. # Terminate processes
  59. for p in procs:
  60. p.terminate()
  61. return result
  62. __all__ = ['getprime']
  63. if __name__ == '__main__':
  64. print('Running doctests 1000x or until failure')
  65. import doctest
  66. for count in range(100):
  67. (failures, tests) = doctest.testmod()
  68. if failures:
  69. break
  70. if count and count % 10 == 0:
  71. print('%i times' % count)
  72. print('Doctests done')