Make multiple threads exec a single command

问题内容:

I’m actually working on a little script that creates dummy files, used to fill a disk (usb key in general), for security purpose.

Actually, I use the threading module, and even if I kind of know how to use it, I’m still struggling with something.

Here’s a bit of code that introduce my problem.

import sys

if sys.version_info[0] >= 3: # Check Python's version, and dismiss Python 3
    raise Exception('You must use Python 2 to launch this program')

from threading import Thread

index = 0

def main():
    multiThreading()

def multiThreading():
    global running
    running = True

    thread1 = Thread(target=fill) # Both threads targets fill()
    thread1.daemon = True
    thread1.start()

    thread2 = Thread(target=fill)
    thread2.daemon = True
    thread2.start()

    while running: # Without this infinite loop, the program exits while the threads are still on, which is not really a problem in this bit of code, 
    # as they finish their tasks, but it is one in the original script. Anyway.
        if running is False:
            return None

def fill(): # this function  normally fills a chosen drive with data
    global index
    while running:
        index += 1
        print index
        if index >= 10:
            global running
            running = False
            # The index is used AFTER index += 1 is executed, which causes a problem


if __name__ == '__main__':
    main()

print 'End'

Which returns

12

34

56

78

910

End
>>> 

The thing is that actually, I want it to print

1

2

3

...

10

End
>>>

But the threads all pass by the index, which adds 2 instead of 1 (2 because there is two thread of course)

I tried with watch dogs, with other functions, but the result is the same.
And also, a one-time watch dog isn’t the solution, as I want to make a loop as many times as needed.

Predicted question: Why use multi-threads ? Because it makes the file creation much more faster.

Do you have a solution ? Thanks a lot for reading !

PS: Please forgive my few English mistakes, not being my mother tongue :p ; double-PS: if you got a better idea for the title, my ears are all open

问题评论:

原文地址:

https://stackoverflow.com/questions/47756139/make-multiple-threads-exec-a-single-command

添加评论

友情链接:蝴蝶教程