python多线程通信邮箱

时间:2018-06-02 13:54:37

标签: 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 !
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

但它不起作用。 ERROR:

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)

1 个答案:

答案 0 :(得分:0)

我在循环中改变了两件事:

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