I have a list of strings and I want to process the strings in a periodic manner.
The period of starting processing a new string is 1 second, and it takes 3 seconds to process a string.
What I expect to observe is that from the 3rd second on, I will see a new result every second until all the strings are processed.
However, what I actually saw was that all the results showed up together when all of them are generated. So the question is, how to modify the code to achieve what I expect to see?
from twisted.internet import reactor, threads
import json
import time
def process(string):
print "Processing " + string + "\n"
time.sleep(3) # simulate computation time
# write result to file; result is mocked by string*3
file_name = string + ".txt"
with open(file_name, "w") as fp:
json.dump(string*3, fp)
print string + " processed\n"
string_list = ["AAAA", "BBBB", "CCCC", "XXXX", "YYYY", "ZZZZ"]
for s in string_list:
# start a new thread every second
time.sleep(1)
threads.deferToThread(process, s)
reactor.run()
Meanwhile, it looks like that the order in which the results are generated isn't consistent with the order in which the strings are processed. I would guess it's just printed out of order but they actually are processed in order. How to verify my guess?
Another trivial thing I noticed is that Processing YYYY
is not printed in the right place. Why is that? (There should be an empty line between it and the previous result.)
Processing AAAA
Processing BBBB
Processing CCCC
Processing XXXX
Processing YYYY
Processing ZZZZ
YYYY processed
CCCC processed
AAAA processed
BBBB processed
XXXX processed
ZZZZ processed