Interaction between Threads in Python, error message " Object is not callable"?

Asked

Viewed 155 times

0

I am doing the interaction of 4 Threads, but when running them at the same time appears the following message:

Object is not callable

That is, the object cannot be called. How to fix it?

Follow the code below.

import time
from threading import Thread

Contador_De_Carros_Da_via_1 = 1
Contador_De_Carros_Da_via_2 = 1
Contador_De_Carros_Da_via_3 = 1
Contador_De_Carros_Da_via_4 = 1

def Thread_Via_1():
    print("Via 1 - Verde")
    Contador_De_Carros_Da_via_1 = Contador_De_Carros_Da_via_1 + 1
    print("Carro ", Contador_De_Carros_Da_via_1)
    time.sleep(1)

def Thread_Via_2():
    print("Via 2 - Verde")
    print("Carro ", Contador_De_Carros_Da_via_2)
    Contador_De_Carros_Da_via_2 = Contador_De_Carros_Da_via_2 + 1
    time.sleep(1)

def Thread_Via_3():
    print("Via 3 - Verde")
    print("Carro ", Contador_De_Carros_Da_via_3)
    Contador_De_Carros_Da_via_3 = Contador_De_Carros_Da_via_3 + 1
    time.sleep(1)

def Thread_Via_4():
    print("Via 4 - Verde")
    print("Carro ", Contador_De_Carros_Da_via_4)
    Contador_De_Carros_Da_via_4 = Contador_De_Carros_Da_via_4 + 1
    time.sleep(1)

x = 4

while x > 0:    
    Thread_Via_1 = Thread(target=Thread_Via_1,args=[5])
    Thread_Via_1.start()
    Thread_Via_2 = Thread(target=Thread_Via_2,args=[5])    
    Thread_Via_2.start()
    Thread_Via_3 = Thread(target=Thread_Via_3,args=[5])
    Thread_Via_3.start()
    Thread_Via_4 = Thread(target=Thread_Via_4,args=[5])
    Thread_Via_4.start()
    x = x - 1

1 answer

0


In doing Thread_Via_N = Thread(...) the variable with that name becomes the object returned by the function Thread, instead, use another variable:

x = 4
while x > 0:    
    tmp = Thread(target=Thread_Via_1,args=[5])
    tmp.start()
    tmp = Thread(target=Thread_Via_2,args=[5])    
    tmp.start()
    # ...
    x = x - 1

Or call the start directly, if you do not need to keep the object saved

x = 4
while x > 0:    
    Thread(target=Thread_Via_1,args=[5]).start()
    Thread(target=Thread_Via_2,args=[5]).start()
    # ...
    x = x - 1
  • Cara solved the problem, but the execution of my 4 threads are disorganized! anyway I thank you for solving the problem.

  • Dude, I had to do it the second way you said it, by putting it. (start) in front, but it only executes once even though it is in a loop with more than one execution.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.