문제

With this global variable defined in the script upper focus

t0 = time.time() ## is global

and this function

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

I'm trying to timestamp every print() of my script with

print(timestamp(t0) + ""...whatever..."")

This works, but when i'm enterring multithreading by

for thread_id in range(win32-safe_os):
... p = Process(target=fonction, args=((thread_id),"test"))
... p.start()
... thread_list.append(p)

in order to

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))

i get this stdout :

[2.70299983025] 297 jpg / 36087 files
[2.75] Enterring multithreading
[2.75] Win32 finds : 2 core(s)
[0.0] Load core 0
[0.0] test on core 0
[0.0] Free core 0
[0.0] Load core 1
[0.0] test on core 1
[0.0] Free core 1

I can see that my call to timestamp() and t0 is working, but not in p.start(). I'm wondering how(, and why) i need to correct ?

PS : I tried with time.clock, but in win32 it refers to the beginning of a THREAD (not a script)/

도움이 되었습니까?

해결책

Each process has a separate instance of the global variable. If you want each process to see the same value, you'll need to pass that value as an argument to each process.

다른 팁

The following code:

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)

...outputs on my Linux machine:

[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

So this would be ok. Could you please send more complete code snippet?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top