Python 3.x Python多线程生产者-消费者模式

Python 3.x Python多线程生产者-消费者模式,python-3.x,multithreading,Python 3.x,Multithreading,我还在学习如何编码,这是我第一次尝试多线程。 我读过很多关于多线程的文章。我觉得这些很有帮助 https://stackoverflow.com/questions/11196367/processing-single-file-from-multiple-processes https://pymotw.com/2/multiprocessing/basics.html https://www.agiliq.com/blog/2013/10/producer-consumer-problem-

我还在学习如何编码,这是我第一次尝试多线程。 我读过很多关于多线程的文章。我觉得这些很有帮助

https://stackoverflow.com/questions/11196367/processing-single-file-from-multiple-processes
https://pymotw.com/2/multiprocessing/basics.html
https://www.agiliq.com/blog/2013/10/producer-consumer-problem-in-python/
https://docs.python.org/3/library/multiprocessing.html
有很多事情要考虑。特别是对于初学者。 不幸的是,当我试图将这些信息付诸实践时。我的代码不太正常

此代码背后的思想是读取simplified.txt,其中包含逗号分隔的数字行。例:0.275,0.28,0.275,0.27536078。 生产者线程读取每一行,并从行尾去除换行符。然后对行中的每个数字进行拆分并分配一个变量。 然后将变量1放入队列中。 使用者线程将拾取队列中的项目,将其平方,然后向日志文件中添加一个条目

我使用的代码来自此模板:

https://www.bogotobogo.com/python/Multithread/python_multithreading_Synchronization_Producer_Consumer_using_Queue.php
这是我目前掌握的代码:

import threading
import queue
import time
import logging
import random
import sys

read_file = 'C:/temp/temp1/simplified.txt'
log1 = open('C:/temp/temp1/simplified_log1.txt', "a+")

logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-9s) %(message)s',)

BUF_SIZE = 10
q = queue.Queue(BUF_SIZE)

class ProducerThread(threading.Thread):
    def __init__(self, name, read_file):
        super(ProducerThread,self).__init__()
        self.name = name
        self.read_file = read_file

    def run(self, read_file):
        while True:
            if not q.full():
                with open(read_file, 'r') as f:
                    for line in f:
                        stripped = line.strip('\n\r')
                        value1,value2,value3,value4,value5,value6,value7 = stripped.split(',')
                        q.put(value1)
                        logging.debug('Putting ' + str(value1) + ' : ' + str(q.qsize()) + ' items in queue')
                        time.sleep(random.random())
        return

class ConsumerThread(threading.Thread):
    def __init__(self, name, value1, log1):
        super(ConsumerThread,self).__init__()
        self.name = name
        self.value1 = value1
        self.log1 = log1
        return

    def run(self):
        while True:
            if not q.empty():
                value1 = q.get()
                sqr_value1 = value1 * value1
                log1.write("The square of " + str(value1) + " is " + str(sqr_value1))
                logging.debug('Getting ' + str(value1) + ' : ' + str(q.qsize()) + ' items in queue')
                time.sleep(random.random())
        return

if __name__ == '__main__':

    p = ProducerThread(name='producer')
    c = ConsumerThread(name='consumer')

    p.start()
    time.sleep(2)
    c.start()
    time.sleep(2)
运行代码时,出现以下错误:

Traceback (most recent call last):
  File "c:/Scripta/A_Simplified_Producer_Consumer_Queue_v0.1.py", line 60, in <module>
    p = ProducerThread(name='producer')
TypeError: __init__() missing 1 required positional argument: 'read_file'
回溯(最近一次呼叫最后一次):
文件“c:/Scripta/A\u简化的\u生产者\u消费者\u队列\u v0.1.py”,第60行,在
p=生产商阅读(name='producer')
TypeError:\uuuu init\uuuu()缺少1个必需的位置参数:“读取文件”
我不知道我还需要在哪里添加“读取文件”。
任何帮助都将不胜感激。提前感谢。

您的
ProducerThread
类需要两个参数(
name
read\u file
)作为构造函数的参数,如其
\uuuu init\uuuuu
方法中定义的,在主块中创建实例时,您只提供第一个此类参数。你的第二节课也有同样的问题


您应该在创建实例时向构造函数提供
read_文件
,或者从构造函数签名中删除它,因为您似乎无论如何都不会使用它(您使用传递到
run
函数中的
read_文件
,但我认为这不正确)。似乎您正试图从线程超类重写该方法,我怀疑该方法是否采用了这样的参数。

感谢UserSeven为我设置了正确的路径。 我认为为了使用外部变量,我需要将它们放在init方法中,然后再放在run方法中。您已经澄清,我只需要在run方法中使用变量。 这是工作代码。我不得不删除while-true:语句,因为我不希望代码永远运行

import threading
import queue
import time
import logging
import random
import sys
import os


read_file = 'C:/temp/temp1/simplified.txt'
log1 = open('C:/temp/temp1/simplified_log1.txt', "a+")

logging.basicConfig(level=logging.DEBUG, format='(%(threadName)-9s) %(message)s',)

BUF_SIZE = 10
q = queue.Queue(BUF_SIZE)

class ProducerThread(threading.Thread):
    def __init__(self, name):
        super(ProducerThread,self).__init__()
        self.name = name

    def run(self):
        with open(read_file, 'r') as f:
            for line in f:
                stripped = line.strip('\n\r')
                value1,value2,value3,value4,value5 = stripped.split(',')
                float_value1 = float(value1)
                if not q.full():
                    q.put(float_value1)
                    logging.debug('Putting ' + str(float_value1) + ' : ' + str(q.qsize()) + ' items in queue')
                    time.sleep(random.random())
        return

class ConsumerThread(threading.Thread):
    def __init__(self, name):
        super(ConsumerThread,self).__init__()
        self.name = name
        return

    def run(self):
        while not q.empty():
            float_value1 = q.get()
            sqr_value1 = float_value1 * float_value1
            log1.write("The square of " + str(float_value1) + " is " + str(sqr_value1))
            logging.debug('Getting ' + str(float_value1) + ' : ' + str(q.qsize()) + ' items in queue')
            time.sleep(random.random())
        return

if __name__ == '__main__':

    p = ProducerThread(name='producer')
    c = ConsumerThread(name='consumer')

    p.start()
    time.sleep(2)
    c.start()
    time.sleep(2)