btlam87
btlam87

Reputation: 83

Can't i start two parallel threads in python, each thread has a forerver loop

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

Upvotes: 2

Views: 525

Answers (1)

Arvind
Arvind

Reputation: 141

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()

Upvotes: 3

Related Questions