如何在进程之间共享日期变量 - 多处理 python

How to share the date variable between processes - Multiprocessing python

我正在尝试在多个进程之间共享日期变量,但我在这样做时遇到了一些问题,

在这种情况下有人可以帮助我吗?

import os
import multiprocessing
from multiprocessing import Value
import datetime
import ctypes
def worker(num):
    print(num.value,'date')
    if(str(num.value) == str(datetime.datetime.now().date())):
        date_flag = 0
    else:
        date_flag = 1
        num.value = str(datetime.datetime.now().date())
    print('this is child',os.getpid())

num = multiprocessing.Value(ctypes.c_wchar_p, '2000-01-01')
print(num.value)

p1 = multiprocessing.Process(target=worker,args=(num,))
p2 = multiprocessing.Process(target=worker,args=(num,))
p1.start()
p2.start()
p1.join()
p2.join()

我在进程启动时分配默认日期,如果系统日期与默认日期不匹配,日期变量应该被覆盖,并且它应该能够访问所有其他进程。

ctypes.c_wchar_p是指针类型。尝试在进程之间共享它会遇到以下问题:

Note: Although it is possible to store a pointer in shared memory remember that this will refer to a location in the address space of a specific process. However, the pointer is quite likely to be invalid in the context of a second process and trying to dereference the pointer from the second process may cause a crash.

摘自 multiprocessing documentation.

解决此问题的一种方法是使用 multiprocessing.Array 而不是 multiprocessing.Value:

import os
import multiprocessing
import datetime
import ctypes

def worker(num):
    print(num[:],'date')
    if(num[:] == str(datetime.datetime.now().date())):
        date_flag = 0
    else:
        date_flag = 1
        num[:] = str(datetime.datetime.now().date())
    print('this is child',os.getpid())

num = multiprocessing.Array(ctypes.c_wchar, '2000-01-01')
print(num[:])

p1 = multiprocessing.Process(target=worker,args=(num,))
p2 = multiprocessing.Process(target=worker,args=(num,))
p1.start()
p2.start()
p1.join()
p2.join()

print(num[:])

使用此方法需要注意的一件事是生成的数组具有 固定大小 ,因此如果不指定,您将无法在其中存储任意长的字符串预先设置大小(通过相应地设置 Array 初始化程序中的第二个参数)。但是,当您使用日期字符串时,这应该没问题,因为它们都具有相同的长度。

另请注意使用 num[:](即 __getslice____setslice__)而不是 num.value