threading.Thread

Pool

lock,condition.event

#!/usr/bin/env python3
# thread.py
# -*- coding: utf-8 -*-

__author__ = 'bravo'

import os,time, random
from multiprocessing import Process
from multiprocessing import Pool
import threading
import os


lock = threading.Lock()

def subproc(name):
    start = time.time();
    print('%s Child(%d) created' % (name,os.getpid()))
    time.sleep(random.random()*3)
    end = time.time()
    print('%s Child(%d) lasts %02f times' % (name,os.getpid(),end-start))


def fork_test():
    print('start')
    pid = os.fork()
    if(pid == 0):
        print('child ', os.getpid(),'with parenet',os.getppid())
    elif (pid > 0):
        print('parent')
    else:
        print('error')


def pool_test():
    print(threading.current_thread().name)
    print('Parent(%d)' % os.getpid())
    p = Pool(1000)
    for i in range(1000):
        p.apply_async(subproc,(i,))
    p.close()
    p.join()
    print('All done')

def thread_test():
    t = threading.Thread(target=pool_test,name='thread for pool')
    t.start()
    t.join()


ev = threading.Event()

def gogogo(item):
    index,ev = item
    if index != 9:
        print('wait',index)
        ev.wait()
    else:
        print('set')
        ev.set()
    time.sleep(index)
    print('item',index)

def start_thread(obj):
        print(obj.isalive())
        return

if __name__ == '__main__':
    # thread prepare 注意参数如何传递的,线程函数不能用用*arg **kwds来作参数
    thread_l = [threading.Thread(target = gogogo,args = ([i,ev],)) \
     for i in range(10)]

    # lambda同时启动, map后得到的是iterator,需要list下才真正执行
    list(map(lambda obj:obj.join(),thread_l))
    #fork_test()
    #poll_test()
    # thread_test()
    input('end')