python 通过邮箱进行多线程通信

python multithreading comunication throught mailbox

我想制作一个有 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)

我在 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