Python - Threads

From Torben's Wiki
Jump to: navigation, search

Parallel computation using multiple processes (threads via module "threading" seem to run only on one cpu) for usage of multiple cpu cores. From [1]

Prob: KeyboardInterrupt (CTRL+C) does not close program completely see [2] as starting point for a solution

from multiprocessing import Pool

def escapes(cr, ci, it):
    """Does iterating z <- z^2 + c escape after it iterations?"""
    zr = 0.0
    zi = 0.0
    for i in xrange(it):
        # z <- z^2 + c
        zr,zi = zr*zr - zi*zi + cr, 2*zr*zi + ci
        if zr*zr + zi*zi > 4:
            return True
    return False

def toChar(p):
    if p: return " "
    else: return "X"

def doRow((xmin,xmax,xstep, ymin,ymax,ystep, iterations, yc)):
    """Calculate one row of the output."""
    y = yc*(ymax-ymin)/ystep + ymin
    row = []
    for xc in xrange(xstep):
        x = xc*(xmax-xmin)/xstep + xmin
        row.append( escapes(x, y, iterations) )
    return "".join([toChar(p) for p in row])

def mandel(xmin,xmax,xstep, ymin,ymax,ystep, iterations):
    """Calculate and print a Mandelbrot set."""
    pool = Pool()  # askes the os for num of cpus ;-)
    results = []
    for yc in xrange(ystep):
        res = pool.apply_async(doRow, ((xmin,xmax,xstep, ymin,ymax,ystep, iterations, yc),))
        results.append(res)
    for yc in xrange(ystep):
        print results[yc].get()

if __name__=="__main__":
    mandel(-2.0, 1.0, 80, -1.0, 1.0, 24, 20000)
Personal tools