【问题标题】:python multithreading comunication throught mailboxpython通过邮箱进行多线程通信
【发布时间】:2025-12-14 13:50:02
【问题描述】:

我想创建一个具有 10 个线程的应用程序,这些线程通过邮箱在它们之间进行 2 个 2 个通信。一个线程将消息写入文件,另一个线程读取它。期望的输出:

Thread  1 writes message: Q to file:  testfile.txt !
Thread  2 : Q
Thread  3 writes message: Q to file:  testfile.txt !
Thread  4 : Q
Thread  5 writes message: Q to file:  testfile.txt !
Thread  6 : Q
Thread  7 writes message: Q to file:  testfile.txt !
Thread  8 : Q
Thread  9 writes message: Q to file:  testfile.txt !
Thread  10 : Q

但它不起作用。错误:

TypeError: read() argument after * must be an iterable, not int

我可以做些什么来解决我的问题?我的代码:

# -*- coding: utf-8 -*-
import threading
import time    


def write(message, i):
    print "Thread  %d writes message: %s to file:  %s !" % (i, 'Q', 'testfile.txt')     
    file = open("testfile.txt","w")
    file.write(message)
    file.close()
    return


def read(i):
    with open("testfile.txt", 'r') as fin:
            msg = fin.read()
    print "Thread  %d : %s \n" % (i, msg)
    return


while 1:
    for i in range(5):
        t1 = threading.Thread(target=write, args=("Q", int(2*i-1)))
        t1.start()

        time.sleep(0.2)

        t2 = threading.Thread(target=read, args=(int(2*i)))
        t2.start()

        time.sleep(0.5)

【问题讨论】:

    标签: python multithreading ipc python-multithreading


    【解决方案1】:

    我在 while 循环中更改了两件事:

    1) 如果您希望第一个线程为Thread 1,则应传递 2i+1 和 2i+2

    2) 如果你想给函数传递参数,你应该传递可迭代的数据类型。简单地说,在int(2*i+2) 后面加一个逗号。

    while 1:
        for i in range(5):
            t1 = threading.Thread(target=write, args=("Q", int(2*i+1)))
            t1.start()
            t1.join()
            time.sleep(0.5)
    
            t2 = threading.Thread(target=read, args=(int(2*i+2),))
            t2.start()
            t2.join()
            time.sleep(0.5)
    

    输出:

    Thread  1 writes message: Q to file:  testfile.txt !
    Thread  2 : Q
    
    Thread  3 writes message: Q to file:  testfile.txt !
    Thread  4 : Q
    
    Thread  5 writes message: Q to file:  testfile.txt !
    Thread  6 : Q
    
    Thread  7 writes message: Q to file:  testfile.txt !
    Thread  8 : Q
    
    Thread  9 writes message: Q to file:  testfile.txt !
    Thread  10 : Q
    

    【讨论】: