Marco Bob
Marco Bob

Reputation: 61

Python threading library: code executes linearly and not in parallel

I want to run two threads in parallel (on python3.6), which works for following code example:

import threading
from time import sleep

# use Thread to run def in background
# Example:
def func1():
    while True:
        sleep(1)
        print("Working")

def func2():
    while True:
        sleep(2)
        print("Working2")


Thread(target = func1).start()
Thread(target = func2).start()

but it does not work for threading.Thread:

import threading
from time import sleep
# use Thread to run def in background
# Example:
def func1():
    while True:
        sleep(1)
        print("Working")

def func2():
    while True:
        sleep(2)
        print("Working2")


x = threading.Thread(target=func1())
y = threading.Thread(target=func2())
x.start()
y.start()

I would like to use the latter option to check if x or y are still alive.

Upvotes: 0

Views: 50

Answers (1)

ForceBru
ForceBru

Reputation: 44916

There's a difference between Thread(target = func1) (first code) and Thread(target=func1()) (second code):

  • the first one passes the function object to Thread
  • the second one executes the function (because you called it with func1()) and passes its return value to Thread

Since you want the threads to call your functions, don't call them:

x = threading.Thread(target=func1)
y = threading.Thread(target=func2)
x.start()
y.start()

Upvotes: 2

Related Questions