Python 多进程/多线程 学习笔记

【多进程/多线程】
    # 多进程和多线程的区别在于,对于同一个变量,多进程是每个进程都有一份自己的拷贝,而多线程则是共享这个变量。
    #  多线程使用不当有一定数据风险,应该为此加锁
    # 因为 python 解释器带有全局锁 GIL,所以  python 多线程并不能真正实现并发
1)新建一个子进程
    # python 提供了跨平台多进程模块 multiprocessing
    from multiprocessing import Process
    import os
    def newProc(name):    # 定义子进程要调用的函数
        print 'Child process %s is running, PID is %d...' %(name, os.getpid())
    if __name__ == '__main__':    # 若操作系统是 Windows 必须加上这个判断
        print 'Parent process ID is %d' %(os.getpid())
        print 'Creating new process...'
        proc = Process(target = newProc, args = ('CHINA'))    # 创建子进程
        proc.start()    # 启动子进程
        proc.join()    # 等待子进程运行完毕之后再继续执行后续代码
        print 'new process is done.'
2)批量创建子进程
    # 模块 multiprocessing 中的 Pool 函数可以实现批量异步创建线程
    from multiprocessing import Pool
    import os
    def childProc(id):    # 定义子进程要调用的函数
        print 'Child process %d running, PID is %d....' %(id, os.getpid())
    if __name__ == '__main__':    # 若操作系统是 Windows 必须加上这个判断
        print 'Parent process running, PID is %d' %(os.getpid())
        print 'Creating 5 processes now...'
        proc = Pool()
        for i in range(5):
            proc.apply_async(childProc, args = (i, ))    # 创建子进程
        print 'Wating for all child processes done....'
        proc.close()    # 停止添加新的子进程
        proc.join()    # 等待所有子进程运行完毕再执行后续代码
        print 'All child processes are done.'
3)新建线程
    # 模块 threading 中的 Thread 函数可以为进程创建线程
    import threading
    def newThread():    # 定义创建线程中要调用的函数
        print 'NewThread <%s> now running...' %(threading.current_thread().name)
    print 'Parent thread <%s> now running...' %(threading.current_thread().name)
    thr = threading.Thread(target = newThread, name = 'ChildThread')    # 创建线程
    thr.start()    # 启动线程
    thr.join()    # 等待线程结束
    print 'Child thread is done.'
4)为多线程中操作的数据加锁
    # 因为多线程操作时有将数据改乱的风险,所以要对数据加锁保障数据安全
    # 在处理加锁数据时,代码的执行模式是单线程的
    # 模块 threading 中的 Lock 函数可以创建锁
    import threading
    gScore = 100
    threadPool = []
    gScoreLock = threading.Lock()    # 为数据创建锁
    def newThread():    # 定义线程中要调用的函数
        gScoreLock.acquire()    # 尝试获取锁
        try:
            global gScore
            gScore = gScore / 1
            print 'gScore is:', gScore
        finally:
            gScoreLock.release()    # 释放锁
    for i in range(30):    # 数据不加锁的情况下,线程越多数据被改乱的几率越大
        threadPool.append(threading.Thread(target = newThread, name = i))    # 创建线程池
    for i in threadPool:
        i.start()
    for i in threadPool:
        i.join()
    print 'All threads done.'

你可能感兴趣的:(hack,脚本,Python)