0

I'm trying to simplify the code of threads below:

import threading

def test1():
    print("test1")

def test2():
    print('test2')

thread1 = threading.Thread(target=test1)
thread2 = threading.Thread(target=test2)
thread1.start()
thread2.start()
thread1.join()
thread2.join()

So, I want to simplify this part of code below to:

# ...

thread1 = threading.Thread(target=test1)
thread2 = threading.Thread(target=test2)
thread1.start()
thread2.start()
thread1.join()
thread2.join()

Something like one line of code below:

# ...

threading.Threads(test1, test2).start().join()

Are there any ways to do this? and it's ok if it's not one line of code as long as it's simpler.

3
  • Why do you need it to be a one liner? Simpler how? less typing? Commented Oct 26, 2022 at 13:44
  • @wwii. It's just messy. Don't you think so? Commented Oct 26, 2022 at 13:47
  • iterate over a list of targets? Commented Oct 26, 2022 at 14:06

3 Answers 3

2

just write it yourself ...

class Threads:
    def __init__(self,*functions):
        self._functions = functions
        self._threads = []

    def start(self):
        for func in self._functions:
            thread = threading.Thread(target=func)
            self._threads.append(thread)
            thread.start()
        return self

    def join(self):
        for thread in self._threads:
            thread.join()

usage:

Threads(test1, test2).start().join()

Edit: using threadpool is more pythonic

from operator import methodcaller
from multiprocessing.pool import ThreadPool

caller = methodcaller("__call__")
with ThreadPool() as pool:
     results = pool.map(caller, [test1, test2])
Sign up to request clarification or add additional context in comments.

1 Comment

Your "threadpool" way works properly. This is pythonic. Thanks
0
import threading

threads_list = []
for i in range(thread_count)
    thread = threading.Thread(target=target_func, args=(args,))
    thread.start()
    threads_list.append(thread)

Comments

0

You could refactor the functions so that they are the same function but with different inputs, e.g.

def test(s):
    print(s)

Then, you can use higher level ThreadPool api. This calls the test function with each of the elements in the list ['test1', 'test2'] via different threads. So you don't need to manage details such as starting or joining the threads.

from multiprocessing.pool import ThreadPool

with ThreadPool as pool:
     results = pool.map(test, ['test1', 'test2'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.