Python多线程学习

 #time.ctime()得到当前时间,在线程的学习中可用这个函数来理解线程在程序中的运行先后顺序

python线程中可用 threading 来创建线程

t=threading.Thread(target=xxx, args=(xxx,))

t.start() 线程开始

t.join() 等待带线程完成

import time
import threading


def loop1(in1):
    # ctime 得到当前时间
    print("starting loop1 at:", time.ctime())
    print("我是参数 ",in1)
    time.sleep(4)
    print("End loop1 at:", time.ctime())


def loop2(in1,in2):
    print("starting loop2 at:", time.ctime())
    print("我是参数 ", in1,"和参数",in2)
    time.sleep(4)
    print("End loop2 at:", time.ctime())


def main():
    print ("starting at:", time.ctime())
    t1 = threading.Thread(target=loop1, args=("EEE",))
    t1.start()

    t2 = threading.Thread(target=loop2, args=("MMM", "AAA"))
    t2.start()

    t1.join()
    t2.join()

    print("All done at:", time.ctime())


if __name__ == "__main__":
    main()
starting at: Mon Apr 22 22:40:29 2019
starting loop1 at: Mon Apr 22 22:40:29 2019
我是参数  EEE
starting loop2 at: Mon Apr 22 22:40:29 2019
我是参数  MMM 和参数 AAA
End loop1 at: Mon Apr 22 22:40:33 2019
End loop2 at: Mon Apr 22 22:40:33 2019
All done at: Mon Apr 22 22:40:33 2019

Process finished with exit code 0
import time
import threading


def fun():
    print("start fun")
    time.sleep(2)
    print("end fun")


print("Main thread")

t1 = threading.Thread(target=fun, args=())
t1.setDaemon(True)
t1.start()

time.sleep(1)
print("Main thread end")

 以下分别是不注释 t1.setDaemon(True) 和注释的结果

Main thread
start fun
Main thread end
Main thread
start fun
Main thread end
end fun

我们可以得到当将子线程设定为守护线程,则该子线程在主线程结束时自动结束。

这里需要注意的是将子线程设置成守护线程必须在线程start前设置

threading.currentThread :返回当前线程变量

threading.enmerate :返回一个包含正在运行的线程的list,正在运行的线程指的是线程启动后,结束前

threading.activeCount: 返回正在运行的线程数量,效果跟len(threading.enmerate)相同

thr.setName :给线程设置名字

thr.getName :得到线程的名字

import time
import threading


def loop1():
    print("starting loop1 at:", time.ctime())
    time.sleep(2)
    print("End loop1 at:", time.ctime())


def loop2():
    print("starting loop2 at:", time.ctime())
    time.sleep(4)
    print("End loop2 at:", time.ctime())


def main():
    print ("starting at:", time.ctime())
    t1 = threading.Thread(target=loop1, args=())
    t1.setName("THR_1")
    t1.start()
    t2 = threading.Thread(target=loop2, args=())
    t2.setName("THR_2")
    t2.start()

    for thr in threading.enumerate():
        print("正在运行的线程名字是:{0}".format(thr.getName()))

    print("正在运行的自线程的数量为{}".format(threading.activeCount()))

    print("All done at:", time.ctime())


if __name__ == "__main__":
    main()

输出结果

starting at: Tue Apr 23 20:15:23 2019
starting loop1 at: Tue Apr 23 20:15:23 2019
starting loop2 at: Tue Apr 23 20:15:23 2019
正在运行的线程名字是:MainThread
正在运行的线程名字是:THR_1
正在运行的线程名字是:THR_2
正在运行的自线程的数量为3
All done at: Tue Apr 23 20:15:23 2019
End loop1 at: Tue Apr 23 20:15:25 2019
End loop2 at: Tue Apr 23 20:15:27 2019

可以在这将线程t1修改为守护线程或中途停止等多种方式来实验

下面是一个案例 一开始出现了 TypeError: ThreadFunc() takes no arguments的问题 原因是在类里 init两边都有两个_

还有为函数插入文档解释将鼠标放函数上出现小灯泡选择Insert documentation string stub

以下为线程的高级点的应用

import threading
from time import sleep, ctime


loop = [4, 2] #第一次延迟四秒,第二次延迟2秒


class ThreadFunc:

    def __init__(self, name):
        self.name = name

    def loop(self, nloop, nsec):
        """

        :param nloop:loop 函数的名称
        :param nsec: 系统休眠时间
        """
        print('Start loop',nloop,'at',ctime())
        sleep(nsec)
        print('Done loop',nloop,'at',ctime())


def main():
    print("Start at:", ctime())

    # ThreadFunc("loop").loop 跟以下两个式子相等
    # t = ThreadFunc("loop")
    # t.loop
    # 以下t1和t2的定义方式相同
    t = ThreadFunc("loop")
    t1 = threading.Thread(target=t.loop, args=("LOOP1", 4))
    # 下面的这种写法更西方人,工业化一点
    t2 = threading.Thread(target=ThreadFunc('loop').loop, args=("LOOP2", 2))

    # 常见错误的写法
    # t1 = threading.Thread(target=ThreadFunc('loop').loop(100,4))
    # t2 = threading.Thread(target=ThreadFunc('loop').loop(100, 2))

    t1.start()
    t2.start()

    t1.join()
    t2.join()

    print("ALL done at:", ctime())


if __name__ == '__main__':
    main()
Start at: Wed Apr 24 00:04:49 2019
Start loop LOOP1 at Wed Apr 24 00:04:49 2019
Start loop LOOP2 at Wed Apr 24 00:04:49 2019
Done loop LOOP2 at Wed Apr 24 00:04:51 2019
Done loop LOOP1 at Wed Apr 24 00:04:53 2019
ALL done at: Wed Apr 24 00:04:53 2019

程序运行时如果多个线程对同一个对象进行操作,可能会出现一些混乱。在多线程中引入锁来对线程进行控制,便于线程同步。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值