import subprocess
import time
import os
import threading

def runTest():
    procs = []
    lock = threading.Lock()
    def task():
        myprocs = []
        for x in xrange(10):
            proc = subprocess.Popen(
                'ls /bin',
                shell = True,
                executable = '/bin/sh',
                env = os.environ,
                close_fds = True,
                stdout = subprocess.PIPE,
                stderr = subprocess.PIPE)
            myprocs.append(proc)
        with lock:
            procs.extend(myprocs)        
    start = time.time()
    th = []
    for x in xrange(4):
        th.append(threading.Thread(target=task))
    for t in th:
        t.start()    
    for t in th:
        t.join()    
    print 'popen: %.3f' % (time.time() - start)

    start = time.time()                      
    for proc in procs:
        proc.wait()
    print 'wait: %.3f' % (time.time() - start)

mem = []
def allocMem():
    # let's allocate tons of memory
    global mem
    mem = []
    for x in xrange(10000):
        mem.append([None] * 10000)
    print 'mem allocated'

if __name__ == '__main__':
    runTest()
    allocMem()
    runTest()
