#scriptA.py: import time from multiprocessing import sharedmemory, Process def main():…
- User
#scriptA.py:
import time from multiprocessing import shared_memory, Process
def main(): # Cria uma memória compartilhada para o inteiro e lê o valor inicial dele int_shm = shared_memory.SharedMemory(name='numeroA') numeroA = shared_memory.RawValue('i', 0) numeroA = shared_memory.RawValue('i', numeroA.value)
# Cria uma memória compartilhada para a string e lê o valor inicial dela str_shm = shared_memory.SharedMemory(name='nomeA') nomeA = shared_memory.RawArray('c', b'nome original') nomeA = shared_memory.RawArray('c', nomeA) # Define a função que será executada pelo processo filho def scriptB(numeroA, nomeA): while True: print('—scriptB—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(3) # Cria o processo filho processB = Process(target=scriptB, args=(numeroA, nomeA)) processB.start() while True: # Modifica os valores das variáveis compartilhadas numeroA.value += 1 nomeA.value = b"novo nome" print('—scriptA—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(5)[WinError 2] O sistema não conseguiu localizar o ficheiro especificado: 'numeroA' File "C:\meu\scripta.py", line 100, in main int_shm = shared_memory.SharedMemory(name='numeroA') File "C:\meu\scripta.py", line 136, in main() FileNotFoundError: [WinError 2] O sistema não conseguiu localizar o ficheiro especificado: 'numeroA' # Libera a memória compartilhada int_shm.close() str_shm.close()
if name == "main": main()
- Assistant
The code seems to be attempting to create and use shared memory for inter-process communication between two scripts. However, there is an error raised stating that the system cannot locate the specified file 'numeroA'.
The error occurs because the code is trying to access the shared memory with the name 'numeroA' without actually creating it beforehand. In order to use shared memory, you should first create it using shared_memory.SharedMemory() and then pass the name of the shared memory to other processes to access it.
To fix the error, you need to modify the code as follows:
scriptA.py
import time from multiprocessing import shared_memory, Process
def main(): # Create a shared memory for the integer and read its initial value int_shm = shared_memory.SharedMemory(name='numeroA', create=True, size=sizeof(c_int)) numeroA = shared_memory.RawValue('i', 0, True)
# Create a shared memory for the string and read its initial value str_shm = shared_memory.SharedMemory(name='nomeA', create=True, size=sizeof(c_char) * 13) nomeA = shared_memory.RawValue('c', b'nome original', True) def scriptB(numeroA, nomeA): while True: print('—scriptB—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(3) processB = Process(target=scriptB, args=(numeroA, nomeA)) processB.start() while True: numeroA.value += 1 nomeA.value = b"novo nome" print('—scriptA—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(5) # Free the shared memory int_shm.close() str_shm.close()if name == "main": main()
In the modified code, the
nameparameter ofshared_memory.SharedMemory()is used along withcreate=Trueto create the shared memory. Additionally, thesizeparameter is used to specify the size of the shared memory. After creating the shared memory, it is used to initialize thenumeroAandnomeAvariables. - User
Exception has occurred: NameError name 'sizeof' is not defined File "C:\meu\scripta.py", line 100, in main int_shm = shared_memory.SharedMemory(name='numeroA', create=True, size=sizeof(c_int)) File "C:\meu\scripta.py", line 136, in main() NameError: name 'sizeof' is not defined
- Assistant
I apologize for the error. The
sizeoffunction is part of thectypesmodule, which you need to import in order to use it.To fix the error, add the following import statement at the beginning of your script:
from ctypes import sizeof, c_int, c_charHere's the modified code with the import statement added:
import time from ctypes import sizeof, c_int, c_char from multiprocessing import shared_memory, Process def main(): # Create a shared memory for the integer and read its initial value int_shm = shared_memory.SharedMemory(name='numeroA', create=True, size=sizeof(c_int)) numeroA = shared_memory.RawValue('i', 0, True) # Create a shared memory for the string and read its initial value str_shm = shared_memory.SharedMemory(name='nomeA', create=True, size=sizeof(c_char) * 13) nomeA = shared_memory.RawValue('c', b'nome original', True) def scriptB(numeroA, nomeA): while True: print('—scriptB—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(3) processB = Process(target=scriptB, args=(numeroA, nomeA)) processB.start() while True: numeroA.value += 1 nomeA.value = b"novo nome" print('—scriptA—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(5) # Free the shared memory int_shm.close() str_shm.close() if __name__ == "__main__": main()With this modification, the
sizeoffunction should be defined and the code should run without theNameErrorexception. - User
Exception has occurred: AttributeError module 'multiprocessing.shared_memory' has no attribute 'RawValue' File "C:\meu\scripta.py", line 102, in main numeroA = shared_memory.RawValue('i', 0, True) File "C:\meu\scripta.py", line 137, in main() AttributeError: module 'multiprocessing.shared_memory' has no attribute 'RawValue'
- Assistant
I apologize for the confusion. You are correct that the
multiprocessing.shared_memorymodule does not have aRawValuefunction. Instead, we can usemultiprocessing.Valueto create a shared variable.Here's the modified code:
import time from ctypes import sizeof, c_int, c_char from multiprocessing import shared_memory, Process, Value def main(): int_shm = shared_memory.SharedMemory(name='numeroA', create=True, size=sizeof(c_int)) numeroA = Value('i', 0, lock=True) str_shm = shared_memory.SharedMemory(name='nomeA', create=True, size=sizeof(c_char) * 13) nomeA = Value('c', b'nome original', lock=True) def scriptB(numeroA, nomeA): while True: print('—scriptB—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(3) processB = Process(target=scriptB, args=(numeroA, nomeA)) processB.start() while True: with numeroA.get_lock(): numeroA.value += 1 with nomeA.get_lock(): nomeA.value = b"novo nome" print('—scriptA—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(5) int_shm.close() str_shm.close() if __name__ == "__main__": main()In the modified code, I replaced
shared_memory.RawValuewithmultiprocessing.Value. Thelock=Trueparameter is added to ensure thread-safe access to the shared variables.I also used
numeroA.get_lock()andnomeA.get_lock()to acquire locks before modifying the shared variables in the main process. This helps in preventing race conditions when accessing the shared variables concurrently.This should fix the
AttributeErrorand allow you to use shared variables in your code. - User
Exception has occurred: TypeError one character bytes, bytearray or integer expected File "C:\meu\scripta.py", line 108, in main nomeA = Value('c', b'nome original', lock=True) File "C:\meu\scripta.py", line 138, in main() TypeError: one character bytes, bytearray or integer expected
- Assistant
I apologize for the mistake. The
Valuefunction from themultiprocessingmodule only supports a single character for the type when using the'c'type code. In order to store a string of more than one character in shared memory, we need to usemultiprocessing.Arrayinstead.Here's the modified code:
import time from ctypes import sizeof, c_int, c_char from multiprocessing import shared_memory, Process, Value, Array def main(): int_shm = shared_memory.SharedMemory(name='numeroA', create=True, size=sizeof(c_int)) numeroA = Value('i', 0, lock=True) str_shm = shared_memory.SharedMemory(name='nomeA', create=True, size=sizeof(c_char) * 13) nomeA = Array(c_char, b'nome original', lock=True) def scriptB(numeroA, nomeA): while True: print('—scriptB—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(3) processB = Process(target=scriptB, args=(numeroA, nomeA)) processB.start() while True: with numeroA.get_lock(): numeroA.value += 1 with nomeA.get_lock(): nomeA.value = b"novo nome" print('—scriptA—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(5) int_shm.close() str_shm.close() if __name__ == "__main__": main()In the modified code, I used
multiprocessing.Arrayto create the shared memory for the string variablenomeA. The type codec_charis used to specify that each element in the array is a single character. The initial value for the array is given asb'nome original'.Now, the code should run without the
TypeErrorand allow you to use shared variables for integer and string values. - User
Exception has occurred: AttributeError Can't pickle local object 'main..scriptB' File "C:\meu\scripta.py", line 121, in main processB.start() File "C:\meu\scripta.py", line 138, in main() AttributeError: Can't pickle local object 'main..scriptB'
- Assistant
I apologize for the mistake. The
AttributeErroroccurs because thescriptBfunction cannot be pickled, which is necessary for it to be used as a target function for a new process.To resolve this issue, you can define the
scriptBfunction outside themain()function, making it a top-level function. This way, it can be pickled and used as the target function for the new process.Here's the modified code:
import time from ctypes import sizeof, c_int, c_char from multiprocessing import shared_memory, Process, Value, Array def scriptB(numeroA, nomeA): while True: print('—scriptB—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(3) def main(): int_shm = shared_memory.SharedMemory(name='numeroA', create=True, size=sizeof(c_int)) numeroA = Value('i', 0, lock=True) str_shm = shared_memory.SharedMemory(name='nomeA', create=True, size=sizeof(c_char) * 13) nomeA = Array(c_char, b'nome original', lock=True) processB = Process(target=scriptB, args=(numeroA, nomeA)) processB.start() while True: with numeroA.get_lock(): numeroA.value += 1 with nomeA.get_lock(): nomeA.value = b"novo nome" print('—scriptA—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(5) int_shm.close() str_shm.close() if __name__ == "__main__": main()In the modified code, the
scriptBfunction is defined outside themain()function scope. This allows it to be pickled and used as the target function for the new process.With this modification, the code should run without the
AttributeErrorand both thescriptAandscriptBprocesses should be able to communicate through the shared variables. - User
Estou confuso. Exponha-me as coisas como deve ser. tenho #scriptA.py:
import time from ctypes import sizeof, c_int, c_char from multiprocessing import shared_memory, Process, Value, Array
Define a função que será executada pelo processo filho
def scriptB(numeroA, nomeA): while True: print('—scriptB—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(3)
def main(): # Cria uma memória compartilhada para o inteiro e lê o valor inicial dele int_shm = shared_memory.SharedMemory(name='numeroA', create=True, size=sizeof(c_int)) numeroA = Value('i', 0, lock=True) #numeroA = shared_memory.RawValue('i', 0, True) #numeroA = shared_memory.RawValue('i', numeroA.value)
# Cria uma memória compartilhada para a string e lê o valor inicial dela str_shm = shared_memory.SharedMemory(name='nomeA', create=True, size=sizeof(c_char) * 13) nomeA = Array(c_char, b'nome original', lock=True) #nomeA = shared_memory.RawArray('c', nomeA) # Cria o processo filho processB = Process(target=scriptB, args=(numeroA, nomeA)) processB.start() while True: # Modifica os valores das variáveis compartilhadas with numeroA.get_lock(): numeroA.value += 1 with nomeA.get_lock(): nomeA.value = b"novo nome" print('—scriptA—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(5) # Libera a memória compartilhada int_shm.close() str_shm.close()if name == "main": main() este script ainda é necessário.: #scriptB.py:
import time from multiprocessing import shared_memory
def main(): # Cria uma memória compartilhada para o inteiro e escreve um valor inicial nele int_shm = shared_memory.SharedMemory(name='numeroA') numeroA = shared_memory.RawValue('i', 0) numeroA = shared_memory.RawValue('i', numeroA.value)
# Cria uma memória compartilhada para a string e escreve um valor inicial nela str_shm = shared_memory.SharedMemory(name='nomeA') nomeA = shared_memory.RawArray('c', b'nome original') nomeA = shared_memory.RawArray('c', nomeA) while True: print("—scriptB—") print(f"numeroA: {numeroA.value}") print(f"nomeA: {nomeA.value.decode()}") time.sleep(3) # Libera a memória compartilhada int_shm.close() str_shm.close()if name == "main": main()
- Assistant
Claro, vou simplificar as coisas para você. Aqui está o código revisado:
No arquivo
scriptA.py:import time from ctypes import sizeof, c_int, c_char from multiprocessing import shared_memory, Process, Value, Array # Define a função que será executada pelo processo filho def scriptB(numeroA, nomeA): while True: print('—scriptB—') print(f'numeroA: {numeroA.value}') print(f'nomeA: {nomeA.value.decode()}') time.sleep(3) def main(): # Cria uma memória compartilhada para o inteiro e lê o valor inicial dele int_shm = shared_memory.SharedMemory(name='numeroA', create=True, size=sizeof(c_int)) numeroA = Value('i', 0, lock=True) # Cria uma memória compartilhada para a string e lê o valor inicial dela str_shm = shared_memory.SharedMemory(name='nomeA', create=True, size=sizeof(c_char) * 13) nomeA = Array(c_char, b'nome original', lock=True) # Cria o processo filho processB = Process(target=scriptB, args=(numeroA, nomeA)) processB.start() while True: # Modifica os valores
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.