简体   繁体   中英

How to share the date variable between processes - Multiprocessing python

i'm trying to share the date variable between multiple process, but i'm facing some issue while doing that,

can someone help me in this case?

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

i'm allocating default date when the process is initiaited, date variable should overwrite if system date is not matched with the default date and it should able to access all other process.

ctypes.c_wchar_p is a pointer type. Trying to share it between processes runs into the following issue:

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.

Taken from the multiprocessing documentation .

One way to get around this is to use a multiprocessing.Array instead of the 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[:])

One thing to be aware of with this method is that the resulting array has a fixed size , so you won't be able to store arbitrarily long strings in it without specifying the size in advance (by setting the second parameter in the Array initialiser accordingly). However, as you are working with date strings, this should be fine as they all have the same length.

Note also the use of num[:] (ie __getslice__ and __setslice__ ) instead of num.value .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM