Search code examples
pythonpython-multiprocessingctypes

How to share a string using Python 3's multiprocessing.Value?


I am trying to share a string between two processes using Value, but it does not work.

from multiprocessing import Value, Process
import time
import ctypes
def say_hi(v):
    with v.get_lock():
        print(f"Saying hi with {v.value=:}")
        v.value = "borat"

if __name__ == "__main__":
    v = Value(ctypes.c_wchar_p, "boris")
    p1 = Process(target=say_hi, args=(v,))
    p2 = Process(target=say_hi, args=(v,))

    p1.start()
    p1.join()

    p2.start()
    p2.join()

The first process is supposed to set the string to "borat" but the output is:

Saying hi with v.value=boris

Saying hi with v.value=


Solution

  • It seems that you need to use c_char_p type for this operation (then you can perform decoding):

        from multiprocessing import Value, Process
        import time
        import ctypes
        def say_hi(v):
            with v.get_lock():
                print(f"Saying hi with v.value={v.value.decode()}.")
                v.value = b'borat'
        
        if __name__ == "__main__":
            v = Value(ctypes.c_char_p, b"boris")
            p1 = Process(target=say_hi, args=(v,))
            p2 = Process(target=say_hi, args=(v,))
        
            p1.start()
            p1.join()
        
            p2.start()
            p2.join()