通过邮箱的python多线程通信

通过邮箱的python多线程通信,python,multithreading,ipc,python-multithreading,Python,Multithreading,Ipc,Python Multithreading,我想制作一个有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 !

我想制作一个有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
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) 如果希望第一个线程是
线程1
,则应传递2i+1和2i+2

2) 如果要将参数传递给函数,则应传递iterable数据类型。简单地说,在
int(2*i+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