日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

python中的threading_python中threading超线程用法实例分析

發(fā)布時(shí)間:2024/4/11 python 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python中的threading_python中threading超线程用法实例分析 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

本文實(shí)例講述了python中threading超線程用法。分享給大家供大家參考。具體分析如下:

threading基于Java的線程模型設(shè)計(jì)。鎖(Lock)和條件變量(Condition)在Java中是對(duì)象的基本行為(每一個(gè)對(duì)象都自帶了鎖和條件變量),而在Python中則是獨(dú)立的對(duì)象。Python Thread提供了Java Thread的行為的子集;沒(méi)有優(yōu)先級(jí)、線程組,線程也不能被停止、暫停、恢復(fù)、中斷。Java Thread中的部分被Python實(shí)現(xiàn)了的靜態(tài)方法在threading中以模塊方法的形式提供。

threading 模塊提供的常用方法:

threading.currentThread(): 返回當(dāng)前的線程變量。

threading.enumerate(): 返回一個(gè)包含正在運(yùn)行的線程的list。正在運(yùn)行指線程啟動(dòng)后、結(jié)束前,不包括啟動(dòng)前和終止后的線程。

threading.activeCount(): 返回正在運(yùn)行的線程數(shù)量,與len(threading.enumerate())有相同的結(jié)果。

threading模塊提供的類:

Thread, Lock, Rlock, Condition, [Bounded]Semaphore, Event, Timer, local.

Thread是線程類,與Java類似,有兩種使用方法,直接傳入要運(yùn)行的方法或從Thread繼承并覆蓋run():

1

2

3

4

5

6

7

8

9

10

11

12

13

# encoding: UTF-8

import threading

# 方法1:將要執(zhí)行的方法作為參數(shù)傳給Thread的構(gòu)造方法

def func():

print 'func() passed to Thread'

t= threading.Thread(target=func)

t.start()

# 方法2:從Thread繼承,并重寫(xiě)run()

class MyThread(threading.Thread):

def run(self):

print 'MyThread extended from Thread'

t= MyThread()

t.start()

構(gòu)造方法:

Thread(group=None, target=None, name=None, args=(), kwargs={})

group: 線程組,目前還沒(méi)有實(shí)現(xiàn),庫(kù)引用中提示必須是None;

target: 要執(zhí)行的方法;

name: 線程名;

args/kwargs: 要傳入方法的參數(shù)。

實(shí)例方法:

isAlive(): 返回線程是否在運(yùn)行。正在運(yùn)行指啟動(dòng)后、終止前。

get/setName(name): 獲取/設(shè)置線程名。

is/setDaemon(bool): 獲取/設(shè)置是否守護(hù)線程。初始值從創(chuàng)建該線程的線程繼承。當(dāng)沒(méi)有非守護(hù)線程仍在運(yùn)行時(shí),程序?qū)⒔K止。

start(): 啟動(dòng)線程。

join([timeout]): 阻塞當(dāng)前上下文環(huán)境的線程,直到調(diào)用此方法的線程終止或到達(dá)指定的timeout(可選參數(shù))。

一個(gè)使用join()的例子:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

# encoding: UTF-8

import threading

import time

def context(tJoin):

print 'in threadContext.'

tJoin.start()

# 將阻塞tContext直到threadJoin終止。

tJoin.join()

# tJoin終止后繼續(xù)執(zhí)行。

print 'out threadContext.'

def join():

print 'in threadJoin.'

time.sleep(1)

print 'out threadJoin.'

tJoin= threading.Thread(target=join)

tContext= threading.Thread(target=context, args=(tJoin,))

tContext.start()

運(yùn)行結(jié)果:

in threadContext.

in threadJoin.

out threadJoin.

out threadContext.

希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。

總結(jié)

以上是生活随笔為你收集整理的python中的threading_python中threading超线程用法实例分析的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。