【Python】多线程编程
本文最后更新于 1531 天前,其中的信息可能已经有所发展或是发生改变。

[successbox title=”线程的状态”]

  • 初始化(Init):在创建线程,操作系统在内部会将其标识为初始化状态。此状态只在系统内核中使用。
  • 就绪(Ready):线程已经准备好被执行。
  • 延迟就绪(Deferred ready):表示线程已经被选择在指定的处理器上运行,但还没有被调度。
  • 备用(Standby):表示线程已经被选择下一个在指定的处理器上运行。当该处理器上运行的线程因等待资源等原因被挂起时,调度器将备用线程切换到处理器上运行。只有一个线程可以是备用状态。
  • 运行(Running):表示调度器将线程切换到处理器上运行,它可以运行一个线程周期(quantum),然后将处理器让给其他线程。
  • 等待(Waiting):线程可以因为等待一个同步执行的对象或等待资源等原因切换到等待状态。
  • 过渡(transition):表示线程已经准备好被执行,但它的内核堆已经被从内存中移除。一旦其内核堆被加载到内存中,线程就会变成运行状态。
  • 终止(Terminated):当线程被执行完成后,其状态会变成终止。系统会释放线程中的数据结构和资源。

[/successbox]

一、start_new_thread()函数创建线程。
[sourcecode language=”python” title=”demo20.py”]
import _thread
import time
#为线程定义一个函数
def print_time(threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print("%s: %s" % (threadName, time.ctime(time.time())))
#创建两个线程
try:
_thread.start_new_thread(print_time, ("Thread – 1", 2, ))
_thread.start_new_thread(print_time, ("Thread – 2", 4, ))
except:
print("错误!")
while 1:
pass
[/sourcecode]
效果图:

二、Thread创建线程。
thread 模块已被废弃。用户可以使用 threading 模块代替。所以,在 Python3 中不能再使用”thread” 模块。为了兼容性,Python3 将 thread 重命名为 “_thread”。

threading.Thread类的常用方法
1.在自己的线程类的__ init__里调用threading.Thread.__init__(self,name=threadname),threadname为线程的名字。
2.run(),通常需要重写,编写代码实现做需要的功能。
3.getName(),获得线程对象名称。
4.setName(),设置线程对象名称。
5.start(),启动线程。
6.join([timeout]),等待另一线程结束后再运行。
7.setDaemon(bool),设置子线程是否随主线程一起结束,必须在start()之前调用。默认为False。
8.isDaemon(),判断线程是否随主线程一起结束。
9.isAlive(),检查线程是否在运行中。
[sourcecode language=”python” title=”demo21.py”]
import threading
import time
import _thread

exitFlag = 0
#继承父类threading.Thread
class demo21(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadId = threadID
self.name = name
self.counter = counter
#执行的函数代码
def run(self):
print("Starting" + self.name)
print_time(self.name, self.counter, 5)
print("Exitting" + self.name)
def stop(self):
self.thread_stop = True

def print_time(threadName, delay, counter):
while counter:
if exitFlag:
_thread.exit()
time.sleep(delay)
print(" %s: %s" % (threadName, time.ctime(time.time())))
counter -= 1

#创建新线程
thread1 = demo21(1, "Thread – 1", 1)
thread2 = demo21(2, "Thread – 2", 2)
#开启线程
thread1.start()
thread2.start()
print("Exiting Main Thread")
[/sourcecode]

效果图:

三、线程同步。
使用Threading的Lock(指令锁)和Rlock(可重入锁)对象可以实现简单的线程同步,这两个对象都有acquire方法(申请锁)和release方法(释放锁),对于那些需要每次只允许一个线程操作的数据,可以将其操作放到acquire和release方法之间。

[sourcecode language=”python” title=”demo22.py”]
import threading
import time
class demo22(threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print("Starting " + self.name)
#获得锁,成功获得锁定后返回True
#可选的timeout参数不填时将一直阻塞直到获得锁定
#否则超时后将返回False
#线程阻塞就一直获得锁
threadLock.acquire()
print(self.name, "获得锁")
print_time(self.name, self.counter, 3)
print(self.name, "释放锁")
threadLock.release() #释放锁
def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print(" %s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
threadLock = threading.Lock()
threads = []
#创建新线程
thread1 = demo22(1, "Thread – 1", 1)
thread2 = demo22(2, "Thread – 2", 2)
#开启新线程
thread1.start()
thread2.start()
#添加线程到线程列表
threads.append(thread1)
threads.append(thread2)
#等待所有线程完成
for t in threads:
t.join() #可以阻塞主程序直到线程执行完毕后主程序结束
print("Exiting Main Thread")
[/sourcecode]

效果图:

四、定时器
定时器(Timer)是Thread的派生类,用于在指定的时间后调用一个函数,具体方法如下:timer = threading.Timer(指定时间t,函数f)
timer.start()
执行timer.start()后,程序会在指定的时间t后启动线程执行函数f。
[sourcecode language=”python” title=”demo23.py”]
import threading
import time
def func():
print(time.ctime()) #打印当前的时间
print(time.ctime())
timer = threading.Timer(5, func)
timer.start()
[/sourcecode]

效果图:

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇