Python核心程式設計 第18章 多執行緒

2021-06-29 03:38:44 字數 2469 閱讀 8367

1.對python虛擬機器的訪問由全域性直譯器鎖來控制,正是這個鎖能保證同一時刻只有乙個執行緒在執行。

import threading 

loops = [4,2];

def loop(nloop, nsec):

print 'start loop', nloop, 'at:', ctime();

sleep(nsec);

print 'loop', nloop, 'done at:', ctime();

def main():

print 'starting at:', ctime();

threads = ;

nloops = range(len(loops));

for i in nloops:

t = threading.thread(target=loop, args=(i, loops[i]));

for i in nloops:

threads[i].start();

for i in nloops:

threads[i].join(); #join() wait the thread over.

print 'all none at:', ctime();

if __name__ == '__main__':

main();

建立乙個thread的例項,傳給它乙個可呼叫的類物件。

loops = [4,2];

class threadfunc(object):

def __init__(self, func, args, name=''):

self.name = name;

self.func = func;

self.args = args;

def __call__(self):

def loop(nloop, nsec):

print 'start loop', nloop, 'at:', ctime();

sleep(nsec);

print 'loop', nloop, 'done at:', ctime();

def main():

print 'starting at:', ctime();

threads = ;

nloops = range(len(loops));

for i in nloops:

t = threading.thread(target=threadfunc(loop, (i, loops[i]), loop.__name__));

for i in nloops:

threads[i].start();

for i in nloops:

threads[i].join(); #join() wait the thread over.

print 'all none at:', ctime();

if __name__ == '__main__':

main();

建立新執行緒的時候,thread物件會呼叫threadfunc物件,這時會用到乙個特殊函式__call__()。

從thread派生出乙個子類,建立乙個這個子類的例項。

loops = (4,2);

class mythread(threading.thread):

def __init__(self, func, args, name=''):

threading.thread.__init__(self);

self.name = name;

self.func = func;

self.args = args;

def run(self):

def loop(nloop, nsec):

print 'start loop', nloop, 'at:', ctime();

sleep(nsec);

print 'loop', nloop, 'done at:', ctime();

def main():

print 'starting at:', ctime();

threads = ;

nloops = range(len(loops));

for i in nloops:

t = mythread(loop, (i, loops[i]), loop.__name__);

for i in nloops:

threads[i].start();

for i in nloops:

threads[i].join(); #join() wait the thread over.

print 'all none at:', ctime();

if __name__ == '__main__':

main();

第18章 網路程式設計

第18章 網路程式設計 計算機上面可以安裝非常多的應用軟體,那麼如何區分這些軟體?需要通過埠號來區分,埠號,相當與房子中開的們.一 埠號在計算機裡面有2個位元組那麼大,因此埠號的取值範圍 0 65535 共65536個 但是1024以下的埠號,通常是計算機內建軟體埠 類似於現實生活中的短號號碼 12...

《Python核心程式設計》第10章 習題

10 6.改進的 open 為內建的 open 函式建立乙個封裝.使得成功開啟檔案後,返回檔案控制代碼 若開啟失敗則返回給呼叫者 none 而不是生成乙個異常.這樣你開啟檔案時就不需要額外的異常處理語句 def myopen infile,mode r try fo open infile,mode...

《Python核心程式設計》第14章 習題

14 3.執行環境。建立執行其他python 指令碼的指令碼。filename r d test.py execfile filename 14 4.os.system 呼叫os.system 執行程式。附加題 將你的解決方案移植到subprocess.call import os from sub...