zoukankan      html  css  js  c++  java
  • python-11多线程

    1-多任务可以由多进程完成,也可以由一个进程内的多线程完成。

      1.1多线程代码示例

    import time, threading
    
    def loop():
        print("thread %s is running..." % threading.current_thread().name)
        n=0
        while n<5:
            n = n+1
            print("thread %s >>> %s" % (threading.current_thread().name, n))
            time.sleep(1)
        print("thread %s ended." % threading.current_thread().name)
        
    print("thread %s is running..." % threading.current_thread().name)
    t = threading.Thread(target=loop, name='LookpThread') #创建线程
    t.start() #开始线程
    t.join() #等待线程结束
    print("thread %s ened." % threading.current_thread().name)

      1.2 lock锁的使用

    def run_thread(n):
        for i in range(100000):     
            lock.acquire()  # 先要获取锁:
            try:        
                change_it(n) # 放心地改吧:
            finally:         
                lock.release()   # 改完了一定要释放锁:   
    #Python虽然不能利用多线程实现多核任务,但可以通过多进程实现多核任务。多个Python进程有各自独立的GIL锁,互不影响。

    2-ThreadLocal使用,  线程之间参数传递太麻烦。 所以诞生了它

    import threading
    
    local_school = threading.local() #创建一个全局对象
    
    def process_student():
        stu = local_school.student #根据运行的线程取出student对象
        print("hwllo, %s (in %s)" % (stu, threading.current_thread().name))
    
    def process_thread(name):
        local_school.student = name #每个运行的线程创建的student不一样
        process_student()
    
    t1 = threading.Thread(target=process_thread, args=('fengyong',), name='thread-A')
    t2 = threading.Thread(target=process_thread,args=('binyan',), name='thread-B')
    
    t1.start()
    t2.start()
    t1.join()
    t2.join()

    3-分布式进程

    在Thread和Process中,应当优选Process,因为Process更稳定,而且,Process可以分布到多台机器上,而Thread最多只能分布到同一台机器的多个CPU上。

  • 相关阅读:
    SuperSocket 2.0 发布第一个预览版, 另寻找Yang Fan哥哥
    使用LogMaster4Net实现应用程序日志的集中管理
    博客终结
    我的第一个Socket程序-SuperSocket使用入门(三)
    树莓派 HC-SRO4超声波测距模块的使用
    树莓派 LED+蜂鸣+声音传感器+红外模块组合打造声控/红外控制LED
    Python Django 开发 4 ORM
    Raspberry Pi --操作LED
    Python Django 开发 3 数据库CURD
    Python Django 开发 2 数据库
  • 原文地址:https://www.cnblogs.com/qinzb/p/9045120.html
Copyright © 2011-2022 走看看