Можно ли запустить новый процесс в потоке? - PullRequest
1 голос
/ 13 июля 2020

Я новичок в многопроцессорности / многопоточности, и мне интересно, можете ли вы запустить новый процесс из потока. В частности, у меня есть следующий код, который реализует многопоточную очередь для загрузки данных с использованием ftp. После загрузки данных я хотел бы выполнить задачу с привязкой к ЦП для загруженного файла, но все равно продолжаю загрузку. Проще объяснить в коде, что именно я хочу сделать, поэтому я добавил комментарии ниже, чтобы прояснить свой вопрос:

import queue
import threading
import time

class MyThread(threading.Thread):
    def __init__(self, name):
        threading.Thread.__init__(self)
        self.name = name
    def run(self):
        print('Starting thread %s.' % self.name)
        process_queue()
        print('Exiting thread %s.' % self.name)
        
def process_queue():
    while True:
        try:
            url = my_queue.get(block=False)
            filename = url.split('/')[-1]
            with closing(request.urlopen(url)) as r:
                with open(filename, 'wb') as f:
                    shutil.copyfileobj(r, f)
                    # Here, I'd like to start a new process (if possible) to process the downloaded file, but I'd like to keep the thread going and have it start downloading the next file (which is why I want a new process)
        except queue.Empty:
            return
        
# setting up variables
urls = [
        'ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR824/000/SRR8240860/SRR8240860_1.fastq.gz',
        'ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR824/000/SRR8240860/SRR8240860_2.fastq.gz',
        'ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR824/001/SRR8240861/SRR8240861_1.fastq.gz',
        'ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR824/001/SRR8240861/SRR8240861_2.fastq.gz',
        'ftp://ftp.sra.ebi.ac.uk/vol1/fastq/SRR824/002/SRR8240862/SRR8240862_1.fastq.gz'] 

# filling the queue
my_queue = queue.Queue()

for url in urls:
    my_queue.put(url)

# initializing and starting num_threads threads
num_threads = 10
threads = []

for i in range(num_threads):
    thread = MyThread(i)
    threads.append(thread)
    
for thread in threads:
    thread.start()
    time.sleep(60) # avoid server throttling my downloads

for thread in threads:
    thread.join()
   
...