【问题标题】:Understanding why multithreading could not read a global variable理解为什么多线程无法读取全局变量
【发布时间】:2023-03-25 20:00:02
【问题描述】:

在脚本中定义了这个全局变量

t0 = time.time() ##是全局的

还有这个功能

def 时间戳(t0):
... return ("[" + str(time.time()-t0)+ "] ") ## 从初始开始的时间戳

我正在尝试为脚本的每个 print() 加上时间戳

print(timestamp(t0) + ""...随便..."")

这可行,但是当我进入多线程时

对于范围内的线程 ID(win32-safe_os):
... p = Process(target=fonction, args=((thread_id),"test"))
... p.start()
... thread_list.append(p)

为了

定义函数(thread_id,filetodo):
... print(timestamp(t0)+"加载核心"+str(thread_id))
... print(timestamp(t0)+str(filetodo)+" on core "+str(thread_id))
... print(timestamp(t0)+"空闲内核"+str(thread_id))

我得到了这个标准输出:

[2.70299983025] 297 jpg / 36087 个文件
[2.75] 进入多线程
[2.75] Win32 发现:2 个内核
[0.0] 加载内核 0
[0.0] 对内核 0 进行测试
[0.0] 空闲内核 0
[0.0] 加载核心 1
[0.0] 在核心 1 上测试
[0.0] 空闲核心 1

我可以看到我对 timestamp() 和 t0 的调用正在工作,但在 p.start() 中没有。我想知道如何(以及为什么)我需要更正?

PS:我尝试使用 time.clock,但在 win32 中它指的是 THREAD(不是脚本)的开头/

【问题讨论】:

  • 只是想指出您正在创建一个新进程,而不是一个新线程。
  • 您应该为您的代码使用代码块而不是块引用。将每个代码块缩进 4 个空格。或者选择块并按 CTRL+K。
  • 线程(同一个进程)在共享内存空间中运行,而进程在不同的内存空间中运行。

标签: python multithreading performance win32-process


【解决方案1】:

每个进程都有一个单独的全局变量实例。如果您希望每个进程看到相同的值,则需要将该值作为参数传递给每个进程。

【讨论】:

  • 每个进程都有一个单独的全局变量实例。
  • 是的!完全正确。答案就在问题中,实际上是 "def timestamp(t0):" ... 你摇滚大卫!
【解决方案2】:

以下代码:

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

所以这样就可以了。能否请您发送更完整的代码sn-p?

【讨论】:

  • 在我的 Linux 上也是如此;我正在研究win32进程。我会尝试大卫赫弗曼的解决方案。 THX
猜你喜欢
  • 2015-12-16
  • 1970-01-01
  • 2016-12-27
  • 1970-01-01
  • 1970-01-01
  • 2018-06-24
  • 2021-04-24
  • 1970-01-01
  • 2013-10-21
相关资源
最近更新 更多