Search code examples
pythonmultithreadingperformancewin32-process

Understanding why multithreading could not read a global variable


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


Solution

  • 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.