2013-08-26 48 views
0

隨着劇本上焦點理解爲什麼多線程無法讀取全局變量

T0 =了time.time()##定義這個全局變量是全球

這個功能

DEF時間戳(T0):
...返回( 「[」 + STR(了time.time() - T 0)+ 「]」)##從時間初始啓動

衝壓

我想我的時間戳腳本的每個打印()與

打印(時間戳(T0)+ 「」 ...什麼... 「」)

這工作,但是當我被

在範圍的thread_id enterring多線程(Win32的safe_os):
... p =處理(目標= fonction,ARGS =((的thread_id), 「測試」 ))
... p.start()
... thread_list.append(P)

爲了

DEF fonction(的thread_id,filetodo):
...打印(timestamp(t0)+「加載核心」+ str(thread_id))
... print(timestamp(t0)+ str(filetodo)+「on core」+ str(thread_id))
... print (timestamp(t0)+「Free core」+ str(thread_id))

我得到這個標準輸出:

[2.70299983025] 297 JPG/36087文件
[2.75] Enterring多線程
[2.75]的Win32發現:2芯(S)
[0.0]負載核心0
[0.0]關於核心試驗0
[0.0]免費核心0
[0.0]負載芯1
[0.0]於核心試驗1
[0.0]免芯1

我可以看到,我的呼叫到時間戳()並且t0正在工作,但不在p.start()中。我想知道如何(以及爲什麼)我需要糾正?

PS:我試圖與time.clock,但在Win32中是指一個線程(不是腳本)的開始/

+1

只是想指出你正在創建一個新的進程,而不是一個新的線程。 –

+1

您應該使用代碼塊而不是代碼塊。用4個空格縮進每個代碼塊。或者選擇塊並按下CTRL + K。 –

+0

線程(同一進程)在共享內存空間中運行,而進程在單獨的內存空間中運行。 < - 好的,我明白了...... THX GREG! –

回答

2

每個進程都有全局變量的一個單獨的實例。如果您希望每個進程看到相同的值,則需要將該值作爲參數傳遞給每個進程。

+0

每個進程都有一個單獨的全局變量實例。 < - 我不明白變量的「全局」,所以。謝謝。 –

+0

是的!完全正確。答案就是在這個問題上,實際上是「def timestamp(t0):」......你讓大衛岩石化! –

0

下面的代碼:

import time 
from multiprocessing import Process 

t0 = time.time() ## is global 

def timestamp(t0): 
    return ("[" + str(time.time()-t0)+ "] ") ## time stamping from initial start 

def fonction(thread_id, filetodo): 
    print(timestamp(t0)+"Load core "+str(thread_id)) 
    print(timestamp(t0)+str(filetodo)+" on core "+str(thread_id)) 
    print(timestamp(t0)+"Free core "+str(thread_id)) 

thread_list = [] 
for thread_id in range(2): 
    p = Process(target=fonction, args=((thread_id),"test")) 
    p.start() 
    thread_list.append(p) 

...輸出在我的Linux機器上:

[0.00588583946228] Load core 0 
[0.00625395774841] test on core 0 
[0.00644302368164] Free core 0 
[0.007572889328] Load core 1 
[0.00768899917603] test on core 1 
[0.00770998001099] Free core 1 

所以這會好的。你能否發送更完整的代碼片段?

+0

在我的Linux上,我正在研究win32過程。我會嘗試David Hefferman的解決方案。謝謝 –