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

    Python线程模块 threading

    获取当前线程 threading.current_thread()

    创建线程 threading.Thread(group=none, target=none, name=none, args=(), kwargs={})

    group:线程组,还没有实现,引用时必须是none

    target:要执行的方法名,注意方法名后面不要跟着括号

    name:创建的线程的名字

    args/kwargs:要传入方法的参数

    开始线程 实例.start()

    # _*_ coding:utf-8_*_
    import time
    import threading


    def loop():
    print('thread %s is running...' % threading.current_thread().name)
    n = 0
    while n < 5:
    print('Thread %s >>> %s' % (threading.current_thread().name, n))
    n +=1
    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='loopthread') # 创建线程,target是要执行的方法 name是线程的名称
    t.start() # 开始线程
    t.join()
    print('thread %s ended' % threading.current_thread().name)

    在使用全局变量时,必须给线程加锁 lock,threading.Lock(),不然多线程对全局变量的修改会导致结果出错
    使用线程自己的局部变量时可以不用加锁
    # _*_ coding:utf-8_*_
    import time
    import threading


    def loop():
    print('thread %s is running...' % threading.current_thread().name)
    n = 0
    while n < 5:
    print('Thread %s >>> %s' % (threading.current_thread().name, n))
    n +=1
    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='loopthread') # 创建线程,传入线程执行的函数和参数
    t.start() # 开始线程
    t.join()
    print('thread %s ended' % threading.current_thread().name)

    ThreadLocal全局变量,解决线程之间参数的传递问题
    local_school = threading.local()  # 定义个全局变量


    def process_student():
    std = local_school.student
    print('Hello, %s is in %s' % (std, threading.current_thread().name))


    def process_thread(std):
    local_school.student = std
    process_student()

    std1 = threading.Thread(target=process_thread, name='Thread-A')
    std2 = threading.Thread(target=process_thread, name='Thread-B')
    std1.start()
    std2.start()
    std1.join()
    std2.join()
  • 相关阅读:
    iOS 网络NSURLConnection
    iOS RunLoop
    iOS 多线程及其他补充 02
    iOS 多线程 01
    iOS UI进阶06
    iOS UI进阶05
    ios 调试命令(oc用”po self“,swift用“frame variable self”)
    ios 视频编辑,添加文字、图片(CA动画)水印,合成视频
    ios 添加openssl库
    ios 动效收集
  • 原文地址:https://www.cnblogs.com/xiaohai2003ly/p/8652243.html
Copyright © 2011-2022 走看看