1#!/usr/bin/env python
2
3import mpi4py
4mpi4py.rc.threads = True
5mpi4py.rc.thread_level = "funneled"
6mpi4py.profile('vt-hyb', logfile='threads')
7
8from mpi4py import MPI
9from threading import Thread
10
11MPI.COMM_WORLD.Barrier()
12
13# Understanding the Python GIL
14# David Beazley, http://www.dabeaz.com
15# PyCon 2010, Atlanta, Georgia
16# http://www.dabeaz.com/python/UnderstandingGIL.pdf
17
18# Consider this trivial CPU-bound function
19def countdown(n):
20    while n > 0:
21        n -= 1
22
23# Run it once with a lot of work
24COUNT = 10000000 # 10 millon
25tic = MPI.Wtime()
26countdown(COUNT)
27toc = MPI.Wtime()
28print ("sequential: %f seconds" % (toc-tic))
29
30# Now, subdivide the work across two threads
31t1 = Thread(target=countdown, args=(COUNT//2,))
32t2 = Thread(target=countdown, args=(COUNT//2,))
33tic = MPI.Wtime()
34for t in (t1, t2): t.start()
35for t in (t1, t2): t.join()
36toc = MPI.Wtime()
37print ("threaded:   %f seconds" % (toc-tic))
38