zoukankan      html  css  js  c++  java
  • 【Python】[进程和线程]多进程,多线程,ThreadLocal,进程VS.线程,分布式进程


    1、多进程,multiprocessing模块,
       进程间的通信:Queue[队列],Pipes[管子]
    2、多线程,
       注意:线程公用变量,混乱
       解决方法Lock:因为只有一个锁,所以当要执行统一个函数的时候,只有在解锁的前提下才能

    执行。

    balance = 0
    lock = threading.Lock()
    
    def run_thread(n):
        for i in range(100000):
            # 先要获取锁:
            lock.acquire()
            try:
                # 放心地改吧:
                change_it(n)
            finally:
                # 改完了一定要释放锁:
                lock.release()

    3、ThreadLocal  一个全局变量。
    看代码:

    import threading
    
    # 创建全局ThreadLocal对象:
    local_school = threading.local()
    
    def process_student():
        # 获取当前线程关联的student:
        std = local_school.student
        print('Hello, %s (in %s)' % (std, threading.current_thread().name))
    
    def process_thread(name):
        # 绑定ThreadLocal的student:
        local_school.student = name
        process_student()
    
    t1 = threading.Thread(target= process_thread, args=('Alice',), name='Thread-A')
    t2 = threading.Thread(target= process_thread, args=('Bob',), name='Thread-B')
    t1.start()
    t2.start()
    t1.join()
    t2.join()

    源:http://www.liaoxuefeng.com

  • 相关阅读:
    POJ 1265 Pcik定理
    POJ 1380 坐标旋转
    POJ 1788
    POJ 3714 平面最近点对
    POJ 1905 二分
    POJ 1151 矩形面积并
    POJ 1654 多边形面积
    ZOJ 1010 判断简单多边形+求面积
    about work
    Python 打印 不换行
  • 原文地址:https://www.cnblogs.com/oiliu/p/4757137.html
Copyright © 2011-2022 走看看