2

I have a simple Python3 code, i want to start both function but just only "from_1" ran. Question: how can i manage two threads without .sleep() function, is Python have something to manage.

import threading
def from_1():
    i = 1
    while True:
        print("Thread 1 {}".format(i))
        f = open('face1.jpeg','rb')
        img = f.read()
        f = open('face1_w.jpeg','wb')
        f.write(img)
        f.close()
        i += 1
def from_2():
    i = 1
    while True:
        print("Thread 2 {}".format(i))
        f = open('face2.jpeg','rb')
        img = f.read()
        f = open('face2_w.jpeg','wb')
        f.write(img)
        f.close()
        i-= 1
if __name__ == '__main__':
    jobs = []
    threading.Thread(from_1()).start()
    threading.Thread(from_2()).start()
    

enter image description here

btlam87
  • 83
  • 6
  • It is common to have a `sleep` in every thread, so that you schedule exactly at which time a thread should let other threads take control. Python is going to switch threads even if you don't do that, but it is advisable that you do. Anyway, your bug is that you called `from_1()` before the thread is even constructed. – zvone Sep 08 '20 at 08:51
  • IDK, but you ought to close the files that your code reads from. As shown, it only closes the files that you're writing. Consider using a `with` statement to close the files. https://stackoverflow.com/a/8011836/801894 – Solomon Slow Sep 08 '20 at 17:43

1 Answers1

3

In python the thread constructor should always be called with a keyword argument. So for your program to work you need the target keyword to point to the function the thread needs to run.

import threading
def from_1():
    i = 1
    while True:
        print("Thread 1 {}".format(i))
        f = open('face1.jpeg','rb')
        img = f.read()
        f = open('face1_w.jpeg','wb')
        f.write(img)
        f.close()
        i += 1
def from_2():
    i = 1
    while True:
        print("Thread 2 {}".format(i))
        f = open('face2.jpeg','rb')
        img = f.read()
        f = open('face2_w.jpeg','wb')
        f.write(img)
        f.close()
        i-= 1
if __name__ == '__main__':
    jobs = []
    threading.Thread(target=from_1).start()
    threading.Thread(target=from_2).start()
Arvind
  • 141
  • 3
  • 1
    Exactly. The original code was calling `from_1()` and passing the result of that function to the thread, so it effectively tried to construct a thread after `from_1()` finished. – zvone Sep 08 '20 at 08:54
  • Right, the code gets stuck in the while loop of the `form_1` hence why it never goes to the line that starts the second thread. – Arvind Sep 08 '20 at 09:07