python 多线程之threading

江枫思渺然 提交于 2020-03-02 19:02:16

一些常用函数:

start():开始线程活动。
threading.Lock():创建锁
acquire():线程加锁
release():释放锁
threading.activeCount():返回当前”进程”里面”线程”的个数(包含主进程)
threading.enumerate() :返回当前运行中的Thread对象列表
threading.setDaemon():参数设置为True的话会将线程声明为守护线程,必须在start() 方法之前设置,不设置为守护线程程序会被无限挂起。
join()方法来使得子进程运行结束后再执行父进程

个人比较喜欢创建线程类来实现多线程 来个简单的例子,开2个线程,打印时间,未加锁情况

# -*- coding: UTF-8 -*-
import threading
import time
class MyThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        super(MyThread, self).__init__()
        self.threadID, self.name, self.counter = threadID, name, counter

    def run(self):
        print "进程开始: " + self.name
        self.run_fun(self.name, self.counter, 3)
        print "进程退出:" + self.name

    def run_fun(self, threadName, delay, counter):
        while counter:
            time.sleep(delay)
            print "%s: %s" % (threadName, time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
            counter -= 1

thread1 = MyThread(1, 'thread-1', 1)
thread2 = MyThread(2, 'thread-2', 2)
thread1.start()
thread2.start()
print threading.enumerate()
print "主进程退出"

结果很明显,线程1和线程2同时执行

加锁情况

# -*- coding: UTF-8 -*-
import threading
import time
class MyThread(threading.Thread):
    def __init__(self, threadID, name, counter):
        super(MyThread, self).__init__()
        self.threadID, self.name, self.counter = threadID, name, counter

    def run(self):
        print "进程开始: " + self.name
        threadLock.acquire()  # 获得锁
        self.run_fun()
        threadLock.release()  # 释放锁
        print "进程退出:" + self.name

    def run_fun(self):
        counter = 3
        while counter:
            time.sleep(self.counter)
            print "%s: %s" % (self.name, time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
            counter -= 1

threadLock = threading.Lock()
thread1 = MyThread(1, 'thread-1', 1)
thread2 = MyThread(2, 'thread-2', 2)
thread1.start()
thread2.start()
print threading.enumerate() #显示运行的线程
print "主进程退出"

结果很明显,加锁之后,线程1执行完,线程2才会执行

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!