• python 多进程、多线程


    1、多线程:

      下面讲一个简单用法,这个模块比较简单,但是实际使用中会遇到很多坑

    from multiprocessing import process
    
    
    def go(s):
    	print "主线程 %s " % s
    
    
    if __name__ == "__main__":
    	p = process.Process(target=go, args=(2,))
    	p.start()
    

     

    2、多线程:
      

    from threading import Thread
    
    
    def go(s):
    	print "%s" % s
    
    
    if __name__ == "__main__":
    	t = Thread(target=go, args=(3,))
    	t.start()
    

      注意点:

        args一定是上面例子中的格式;

        这两个模块在使用方法上相似度很高;

    3、线程和进程的区别:

      * 同一个进程内的线程共享代码、数据、文件

      * 在同一个进程内,每个线程有自己的寄存器、栈

    4、多个线程操作相同变量的情况:

      当多个线程操作同一个变量,由于线程的执行顺序不确定,所以返回的不会是预期的数据;

      这个时候就需要线程锁;

      注意:lock可以直接放在函数里,包在函数外没用

      操作数据前r.acquire()

      操作数据后r.release()

    5、死锁、递归锁:

      一个资源被多个线程同时使用,锁使用不当(很容易出现)导致多个线程竞争资源,都获取不到资源,造成死锁;

      rlock(),递归锁,和lock()使用方法相同,但是它会自动计数

     6、信号量

      s=Semaphore(3)

      s.accquire()

      s.release()

      升级版的lock,调用accquire()方法一次,计数-1,调用release一次,计数+1

      当计数为0,会等待到其他线程调用release方法,使计数大于0为止;

    7、threading.Event

      event.isset()   返回状态

      event.wait()  等待event为True

      event.set()  设置event为True

      event.clear()  恢复event值为False

    8、threading.Condition()

      condition = threading.Condition()

      线程a在执行时,竞争线程处于condition.wait(),直到线程a通过condiition.notify("xxxx")通知其他线程,结束等待;

    9、threading.Timer()

      指定n秒后结束

    未完。。。。。。。

      

      

  • 相关阅读:
    密文搜索
    poj 1182 食物链
    1147. Heaps (30)
    1146. Topological Order (25)
    1145. Hashing
    1142. Maximal Clique (25)
    fzu 2112 tickets
    51nod 1554 欧姆诺姆和项链
    codeforces 963B Destruction of a Tree
    hdu 3294 Girls' research
  • 原文地址:https://www.cnblogs.com/chenadong/p/10021830.html
Copyright © 2020-2023  润新知