改错import time from multiprocessing import process class Myprocess(process): def __init__(self,name): super().__init__() # 调用父类的构造方法? self.name=name def run(self) ->None: print(f"a进程ID:{self.pid}") time.sleep(5) if __name__=="__main__": pi = Myprocess("进程1") p2 = Myprocess("进程2") pi.start() p2.start()
时间: 2024-01-18 13:02:55 浏览: 98
这段代码本身没有明显的错误,但是如果要运行,需要在最后加上`pi.join()`和`p2.join()`,等待进程结束。修改后代码如下:
```
import time
from multiprocessing import Process
class MyProcess(Process):
def __init__(self, name):
super().__init__()
self.name = name
def run(self) -> None:
print(f"{self.name}进程ID:{self.pid}")
time.sleep(5)
if __name__ == "__main__":
p1 = MyProcess("进程1")
p2 = MyProcess("进程2")
p1.start()
p2.start()
p1.join()
p2.join()
```
修改的内容包括:
1. 将`process`改为`Process`,因为类名应该首字母大写。
2. 修改了类名`Myprocess`为`MyProcess`,同样是因为类名应该首字母大写。
3. 在最后加上`p1.join()`和`p2.join()`,等待进程结束。
相关问题
import time from multiprocessing import Process from multiprocessing import Manager def sum_range(start, end): total = 0 for i in range(start, end): total += i return total class MyProcess(Process): def __init__(self,st, end, result): self.st = st self.end = end self.result = result super().__init__() def run(self) -> None: total = 0 for i in range(self.st, self.end): total += i self.result.append(total) if __name__ == '__main__': start_time = time.time() manager = Manager() result = manager.list() t1 = MyProcess(1, 50000001,result) t2 = MyProcess(50000001,100000001,result) t1.start() t2.start() t1.join() t2.join() total = sum(result) end_time = time.time() print("并行总和为:", total) print("并行用时:", end_time - start_time, "秒") start_time = time.time() total = sum_range(1,100000001) end_time = time.time() print("串行总和为:", total) print("串行用时:", end_time - start_time, "秒")
这段代码使用了 Python 的 multiprocessing 模块来实现并行计算一个范围内的整数和。它首先定义了一个 sum_range 函数,该函数接受两个参数 start 和 end,然后使用一个 for 循环计算这个范围内所有整数的和,并返回结果。然后它定义了一个名为 MyProcess 的子类,该类继承自 multiprocessing.Process 类,它重写了 run 方法来计算给定范围内的整数和,并将结果存储在一个共享列表中。在主函数中,它使用 multiprocessing.Manager 类来创建共享列表,然后启动两个 MyProcess 实例来并行计算整数和。最后,它计算并打印串行和并行计算的总和和用时。
程序无法执行,修改class Processor(): def __init__(self): self._inspect_step = int(cfg.get('PROCESS', 'INSPECT_STEP')) def capture_img(self): global aco aco = aco + 1 self._cam.stream_on() raw_image = self._cam.data_stream[0].get_image() if raw_image is None: print("Getting image failed.\n") return None print("Frame ID: {} Height: {} Width: {} Count: {}\n" .format(raw_image.get_frame_id(), raw_image.get_height(), raw_image.get_width(), aco - 2)) numpy_image = raw_image.get_numpy_array() if numpy_image is None: return None img = Image.fromarray(numpy_image, 'L') if self._issave: picfile = '{}/{}.bmp'.format(self._picpath, self._piccount) self._piccount = self._piccount + 1 img.save(picfile) if self._isshow: w, h = img.size scale = min(1.0 * IMG_RESIZE_W / w, 1.0 * IMG_RESIZE_H / h) self._img = ImageTk.PhotoImage(image=img.resize((int(w * scale), int(h * scale)), Image.ANTIALIAS)) self._show_cb(self._img) self._cam.stream_off() return img def process_img(self, img): return PROC_OK def inspect(self): print("process2") time.sleep(1) def rotate(self): count = 0 aco = 0 self.threadsignal = 0 while self._running: v = self._dgl.qpin(ROT) if len(v) > 0: count = count + sum(v) if count > self._inspect_step: aco += 1 img = self.capture_img() count = count - self._inspect_step if __name__ == '__main__': task2 = multiprocessing.Process(target=self.inspect) task2.start() task1 = multiprocessing.Process(target=self.rotate) task1.start()
在这段代码中,有几个问题可以被改进。首先,类 `Processor` 中的全局变量 `aco` 可能会导致并发问题,在多进程环境下应该避免使用全局变量。其次,代码中出现了 `time.sleep()`,这会阻塞当前进程并造成性能瓶颈,应该尽量避免使用。
以下是可能的改进方案:
1. 将 `aco` 变量改为实例变量,避免多进程之间的并发问题。
2. 使用 `Queue` 或其他进程间通信机制替代全局变量,避免多进程之间的竞争。
3. 将 `time.sleep()` 改为使用定时器或者事件,避免阻塞进程并提高程序的性能。
4. 在多进程环境中,使用 `if __name__ == '__main__':` 来避免创建子进程时出现递归调用的问题。
以下是修改后的代码示例:
```python
import multiprocessing
from queue import Queue
import time
class Processor():
def __init__(self):
self._inspect_step = int(cfg.get('PROCESS', 'INSPECT_STEP'))
self._aco = 0
self._queue = Queue()
def capture_img(self):
self._aco += 1
self._cam.stream_on()
raw_image = self._cam.data_stream[0].get_image()
if raw_image is None:
print("Getting image failed.\n")
return None
print("Frame ID: {} Height: {} Width: {} Count: {}\n".format(raw_image.get_frame_id(), raw_image.get_height(), raw_image.get_width(), self._aco - 2))
numpy_image = raw_image.get_numpy_array()
if numpy_image is None:
return None
img = Image.fromarray(numpy_image, 'L')
if self._issave:
picfile = '{}/{}.bmp'.format(self._picpath, self._piccount)
self._piccount = self._piccount + 1
img.save(picfile)
if self._isshow:
w, h = img.size
scale = min(1.0 * IMG_RESIZE_W / w, 1.0 * IMG_RESIZE_H / h)
self._img = ImageTk.PhotoImage(image=img.resize((int(w * scale), int(h * scale)), Image.ANTIALIAS))
self._show_cb(self._img)
self._cam.stream_off()
return img
def process_img(self, img):
return PROC_OK
def inspect(self):
print("process2")
while self._running:
time.sleep(1)
self._queue.put("task")
def rotate(self):
count = 0
while self._running:
v = self._dgl.qpin(ROT)
if len(v) > 0:
count = count + sum(v)
if count > self._inspect_step:
self._aco += 1
img = self.capture_img()
count = count - self._inspect_step
try:
task = self._queue.get(block=False)
if task == "task":
print("processing task")
except:
pass
if __name__ == '__main__':
p = Processor()
p._running = True
task2 = multiprocessing.Process(target=p.inspect)
task2.start()
task1 = multiprocessing.Process(target=p.rotate)
task1.start()
```
请注意,这里只是对原始代码的一些修改建议,并不能保证这样的修改能够完全解决问题。在实际环境中,还需要根据具体情况进行调整和优化。
阅读全文