Многопроцессорная функция не записывает в файл или печать - PullRequest
0 голосов
/ 30 декабря 2018

Я работаю над созданием устройства сбора данных Raspberry Pi (3 B +) и пытаюсь создать процесс для записи поступающих данных и записи их в файл.У меня есть функция для записи, которая прекрасно работает, когда я вызываю ее напрямую.

Когда я вызываю ее с использованием многопроцессорного подхода, кажется, ничего не происходит.Я вижу в мониторах задач в Linux, что процесс на самом деле порождается, но файл не записывается, и когда я пытаюсь передать ему флаг, чтобы выключить его, он не работает, то есть я заканчиваю тем, что заканчиваю процесс и ничегокажется, что случилось.

Я прошел через это в разные стороны и не вижу, что я делаю неправильно;кто-нибудь еще?Если это уместно, это функции внутри родительского класса, и одна из функций предназначена для порождения другой в виде потока.

Код, который я использую:

from datetime import datetime, timedelta
import csv
from drivers.IMU_SEN0 import IMU_SEN0
import multiprocessing, os

class IMU_data_logger:
    _output_filename = ''
    _csv_headers = []
    _accelerometer_headers = ['Accelerometer X','Accelerometer    Y','Accelerometer Z']
    _gyroscope_headers = ['Gyroscope X','Gyroscope Y','Gyroscope Z']
    _magnetometer_headers = ['Bearing']
    _log_accelerometer = False
    _log_gyroscope= False
    _log_magnetometer = False
    IMU = None
    _writer=[]
    _run_underway = False
    _process=[]
    _stop_value = 0

def __init__(self,output_filename='/home/pi/blah.csv',log_accelerometer = True,log_gyroscope= True,log_magnetometer = True):
    """data logging device
    NOTE! Multiple instances of this class should not use the same IMU devices simultaneously!"""        
    self._output_filename = output_filename
    self._log_accelerometer = log_accelerometer
    self._log_gyroscope = log_gyroscope
    self._log_magnetometer = log_magnetometer

def __del__(self):
    # TODO Update this
    if self._run_underway: # If there's still a run underway, end it first
        self.end_recording()

def _set_up(self):        
    self.IMU = IMU_SEN0(self._log_accelerometer,self._log_gyroscope,self._log_magnetometer)
    self._set_up_headers()

def _set_up_headers(self):
    """Set up the headers of the CSV file based on the header substrings at top and the input flags on what will be measured"""
    self._csv_headers = []
    if self._log_accelerometer is not None:
        self._csv_headers+= self._accelerometer_headers
    if self._log_gyroscope is not None:
        self._csv_headers+= self._gyroscope_headers
    if self._log_magnetometer is not None:
        self._csv_headers+= self._magnetometer_headers


def _record_data(self,frequency,stop_value):
    self._set_up() #Run setup in thread

    """Record data function, which takes a recording frequency, in herz, as an input"""
    previous_read_time=datetime.now()-timedelta(1,0,0)
    self._run_underway = True # Note that a run is now going
    Period = 1/frequency # Period, in seconds, of a recording based on the input frequency
    print("Writing output data to",self._output_filename)

    with open(self._output_filename,'w',newline='') as outcsv:
        self._writer = csv.writer(outcsv)
        self._writer.writerow(self._csv_headers) # Write headers to file

        while stop_value.value==0: # While a run continues
            if datetime.now()-previous_read_time>=timedelta(0,1,0): # If we've waited a period, collect the data; otherwise keep looping
                print("run underway value",self._run_underway)
            if datetime.now()-previous_read_time>=timedelta(0,Period,0): # If we've waited a period, collect the data; otherwise keep looping
                previous_read_time = datetime.now() # Update previous readtime
                next_row = []
                if self._log_accelerometer:
                    # Get values in m/s^2
                    axes = self.IMU.read_accelerometer_values()
                    next_row += [axes['x'],axes['y'],axes['z']]

                if self._log_gyroscope:
                    # Read gyro values
                    gyro = self.IMU.read_gyroscope_values()
                    next_row += [gyro['x'],gyro['y'],gyro['z']]

                if self._log_magnetometer:
                    # Read magnetometer value
                    b= self.IMU.read_magnetometer_bearing()
                    next_row += b

                self._writer.writerow(next_row)

        # Close the csv when done
        outcsv.close()

def start_recording(self,frequency_in_hz):        
    # Create recording process
    self._stop_value = multiprocessing.Value('i',0)
    self._process = multiprocessing.Process(target=self._record_data,args=(frequency_in_hz,self._stop_value))

    # Start recording process
    self._process.start()
    print(datetime.now().strftime("%H:%M:%S.%f"),"Data logging process spawned")
    print("Logging Accelerometer:",self._log_accelerometer)
    print("Logging Gyroscope:",self._log_gyroscope)
    print("Logging Magnetometer:",self._log_magnetometer)     
    print("ID of data logging process: {}".format(self._process.pid))

def end_recording(self,terminate_wait = 2):
    """Function to end the recording multithread that's been spawned.
    Args: terminate_wait: This is the time, in seconds, to wait after attempting to shut down the process before terminating it."""
    # Get process id
    id = self._process.pid

    # Set stop event for process
    self._stop_value.value = 1

    self._process.join(terminate_wait) # Wait two seconds for the process to terminate
    if self._process.is_alive(): # If it's still alive after waiting
        self._process.terminate()
        print(datetime.now().strftime("%H:%M:%S.%f"),"Process",id,"needed to be terminated.")
    else:
        print(datetime.now().strftime("%H:%M:%S.%f"),"Process",id,"successfully ended itself.")

====================================================================

ОТВЕТ : Оказывается, что для любого, кто здесь пойдет, проблема заключалась в том, что я использовал отладчик VS Code, которыйпо-видимому, не работает с многопроцессорностью и каким-то образом препятствовал успеху порожденного процесса.Большое спасибо Томашу Свайдеру, который помог мне разобраться с проблемами и, в конце концов, нашел мой идиотизм.Помощь была очень признательна !!

1 Ответ

0 голосов
/ 30 декабря 2018

Я вижу несколько неправильных в вашем коде:

Первое, что stop_value == 0 не будет работать как multiprocess.Value ('i', 0)! = 0, измените эту строку на

while stop_value.value == 0

Во-вторых, вы никогда не обновите previous_read_time, поэтому он запишет показания так быстро, как только сможет, вам быстро не хватит диска

В-третьих, попробуйте использовать time.sleep (), что вам нужновыполнение называется занятым циклом, и это плохо, оно тратит впустую циклы ЦП.

Четыре, заканчивающиеся на self._stop_value = 1, вероятно, не будет работать, должен быть другой способ установить это значение, может быть self._stop_value.value = 1.

Вот пример кода, основанного на предоставленном вами коде, который работает просто отлично:

import csv
import multiprocessing
import time
from datetime import datetime, timedelta
from random import randint


class IMU(object):

    @staticmethod
    def read_accelerometer_values():
        return dict(x=randint(0, 100), y=randint(0, 100), z=randint(0, 10))


class Foo(object):

    def __init__(self, output_filename):
        self._output_filename = output_filename
        self._csv_headers = ['xxxx','y','z']
        self._log_accelerometer = True
        self.IMU = IMU()

    def _record_data(self, frequency, stop_value):
        #self._set_up()  # Run setup functions for the data collection device and store it in the self.IMU variable

        """Record data function, which takes a recording frequency, in herz, as an input"""
        previous_read_time = datetime.now() - timedelta(1, 0, 0)
        self._run_underway = True  # Note that a run is now going
        Period = 1 / frequency  # Period, in seconds, of a recording based on the input frequency
        print("Writing output data to", self._output_filename)

        with open(self._output_filename, 'w', newline='') as outcsv:
            self._writer = csv.writer(outcsv)
            self._writer.writerow(self._csv_headers)  # Write headers to file

            while stop_value.value == 0:  # While a run continues
                if datetime.now() - previous_read_time >= timedelta(0, 1,
                                                                    0):  # If we've waited a period, collect the data; otherwise keep looping
                    print("run underway value", self._run_underway)
                if datetime.now() - previous_read_time >= timedelta(0, Period,
                                                                    0):  # If we've waited a period, collect the data; otherwise keep looping
                    next_row = []
                    if self._log_accelerometer:
                        # Get values in m/s^2
                        axes = self.IMU.read_accelerometer_values()
                        next_row += [axes['x'], axes['y'], axes['z']]

                    previous_read_time = datetime.now()
                    self._writer.writerow(next_row)

            # Close the csv when done
            outcsv.close()

    def start_recording(self, frequency_in_hz):
        # Create recording process
        self._stop_value = multiprocessing.Value('i', 0)
        self._process = multiprocessing.Process(target=self._record_data, args=(frequency_in_hz, self._stop_value))

        # Start recording process
        self._process.start()
        print(datetime.now().strftime("%H:%M:%S.%f"), "Data logging process spawned")
        print("ID of data logging process: {}".format(self._process.pid))

    def end_recording(self, terminate_wait=2):
        """Function to end the recording multithread that's been spawned.
        Args: terminate_wait: This is the time, in seconds, to wait after attempting to shut down the process before terminating it."""
        # Get process id
        id = self._process.pid

        # Set stop event for process
        self._stop_value.value = 1

        self._process.join(terminate_wait)  # Wait two seconds for the process to terminate
        if self._process.is_alive():  # If it's still alive after waiting
            self._process.terminate()
            print(datetime.now().strftime("%H:%M:%S.%f"), "Process", id, "needed to be terminated.")
        else:
            print(datetime.now().strftime("%H:%M:%S.%f"), "Process", id, "successfully ended itself.")


if __name__ == '__main__':
    foo = Foo('/tmp/foometer.csv')
    foo.start_recording(20)
    time.sleep(5)
    print('Ending recording')
    foo.end_recording()
...