【问题标题】:multiprocessing, threading gets stuck and printing output gets messed up多处理、线程卡住、打印输出混乱
【发布时间】:2020-09-22 12:52:29
【问题描述】:

我在 python 中运行多个线程。我试过使用线程模块,多处理模块。尽管执行给出了正确的结果,但每次终端卡住并且输出的打印会变得混乱。
这是代码的简化版本。

import subprocess
import threading
import argparse
import sys

result = []

def check_thread(args,components,id):
    for i in components:
        cmd = <command to be given to terminal>
        output = subprocess.check_output([cmd],shell=True)
        result.append((id,i,output))

def check(args,components):
    # lock = threading.Lock()
    # lock = threading.Semaphore(value=1)
    thread_list = []
    for id in range(3):
        t=threading.Thread(target=check_thread, args=(args,components,i))
        thread_list.append(t)

    for thread in thread_list:
        thread.start()

    for thread in thread_list:
        thread.join()

    for res in result:
        print(res)

    return res

if __name__ == 'main':
    parser = argparse.ArgumentParser(....)
    parser.add_argument(.....)
    args = parser.parse_args()
    components = ['comp1','comp2']
    while True:
        print('SELECTION MENU\n1)\n2)\n')
        option = raw_input('Enter option')
        if option=='1':
            res = check(args, components)
        if option=='2':
            <do something else>
        else:
            sys.exit(0)   

我尝试过将多处理模块与 Process、pool 一起使用。尝试将锁传递给 check_thread,尝试从 check_thread() 返回一个值并使用队列接收值,但每次结果相同,执行成功但终端卡住并且打印输出很破旧。
有什么解决办法吗?我正在使用python 2.7。我正在使用 linux 终端。
这是破旧的输出的样子 output

【问题讨论】:

  • 你能给出一个输出例子并解释一下吗?
  • @YusefMaali 我已经添加了输出外观的图像,而且终端在执行后也会卡住
  • 你能把它做成一个完全可运行的例子吗?添加result = []check() 后,该程序对我有用。
  • 您能否包括操作系统、您如何运行它(例如,从命令行)以及额外的 SELECTION MENU 是什么?打印单个列表并显示该菜单的事实表明您的程序中存在其他问题导致问题。
  • @tdelaney 我在代码中添加了更多细节。我有一种感觉,这是导致问题的子进程调用。我想从 subprocess.check_output 获取每个线程的输出,然后将其附加到我的结果中。

标签: python multithreading multiprocessing python-multiprocessing python-multithreading


【解决方案1】:

你应该使用队列模块而不是列表。

import multiprocessing as mp

# Define an output queue
output = mp.Queue()

# define a example function
def function(params, output):
    """ Generates a random string of numbers, lower- and uppercase chars. """
    # Process params and store results in res variable
    output.put(res)

# Setup a list of processes that we want to run
processes = [mp.Process(target=function, args=(5, output)) for x in range(10)]

# Run processes
for p in processes:
    p.start()

# Exit the completed processes
for p in processes:
    p.join()

# Get process results from the output queue
results = [output.get() for p in processes]

print(results)

【讨论】:

  • 这与执行完成之前的结果相同,但是输出在整个终端上以混乱的方式打印,并且终端本身被卡住了。如问题中所述,我之前确实尝试过使用队列,但没有任何帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-09
  • 1970-01-01
  • 1970-01-01
  • 2018-06-13
  • 2020-11-25
  • 2015-07-26
  • 1970-01-01
相关资源
最近更新 更多