【发布时间】:2019-07-22 11:53:39
【问题描述】:
我想使用多个线程创建多个文件,并将数据(在执行某些操作后)从它们各自的线程附加到相应的文件。
我试过了,但是线程之间的数据变得混乱,并且没有将正确的数据添加到相应的文件中。
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
with open('file_'+count+'_logs.txt', 'a+') as result:
result.write("Starting " + self.name)
result.write("Exiting " + self.name)
print ("Starting " + self.name)
print_time(self.name, self.counter, 5)
print ("Exiting " + self.name)
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
myList = ['string0', 'string1', 'string2', 'string3']
if __name__ == "__main__":
count = 0
for data in myList:
count += 1
mythread = myThread(count, "Thread-" + str(count), count)
mythread.start()
mythread.join()
我希望从 4 个线程创建 4 个文件,线程 1 的数据应该写入 file_1_logs.txt 等等... 但是在写入数据时,有时所有数据都写入一个文件中。 如何将这些数据正确写入文件?
【问题讨论】:
-
您的变量
count在线程中不存在。难道你的意思是self.counter? -
count存在于main中,是构造函数的参数 -
我知道,但它在 线程中不存在。该线程确实与主线程分开运行。使用线程时不要使用全局(或更高范围)变量。
-
你是什么意思in线程?
-
这是一个约束,我必须使用更高范围的变量...我从控制我的线程的其他函数获取数据:(
标签: python multithreading python-multithreading file-handling