I tried using a library (common thread) that makes Python's threading package easier to use

I tried using a library (common thread) that makes the Python threading package easier to use. https://pypi.org/project/commonthread/ It's more accurate to try using it or to make it.

Installation method

How to install the commonthread package


pip install -U commonthread

Classes to be installed

First sample (01.py)

01.py


from commonthread import *


# source https://techacademy.jp/magazine/28155
def fibonacci_worker(th: WorkerThread, n: int):
    if n <= 2:
        return 1
    else:
        return fibonacci_worker(th, n - 2) + fibonacci_worker(th, n - 1)


thread = WorkerThread(fibonacci_worker, 36)
thread.name = 'tfib'
thread.start()
success = thread.join(timeout=0.5)
print('success={}'.format(success))
success = thread.join()
print('success={}'.format(success))
print('result={}'.format(thread.result))
print('elapsed={}'.format(thread.elapsed))
print(thread)

01.py execution result


success=False
success=True
result=14930352
elapsed=3.688599109649658
WorkerThread(name=tfib, result=14930352, elapsed=3.688599109649658, args=(36,), kwargs={}, params={})

Explanation (01.py)

Sometimes I want to return a return value from a worker function, so it's optimized for that purpose.

Class-based thread sample (02.py)

02.py


from commonthread import *


# source https://techacademy.jp/magazine/28155
class FibonacciThread(CommonThread):

    def entry(self, n: int):
        if n <= 2:
            return 1
        else:
            return self.entry(n - 2) + self.entry(n - 1)


thread = FibonacciThread(36)
thread.name = 'tfib'
thread.start()
thread.join()
print('result={}'.format(thread.result))
print('elapsed={}'.format(thread.elapsed))
print(thread)

02.py execution result


result=14930352
elapsed=4.399198055267334
FibonacciThread(name=tfib, result=14930352, elapsed=4.399198055267334, args=(36,), kwargs={}, params={})

Commentary (02.py)

Sample class-based thread that defines constructs (03.py)

03.py


from commonthread import *


class AddThread(CommonThread):

    def __init__(self, x: int, y: int):
        CommonThread.__init__(self)
        self.x = x
        self.y = y

    def entry(self):
        time.sleep(2.0)
        return self.x + self.y


thread = AddThread(11, 22)
thread.start()
thread.join()
print('result={}'.format(thread.result))
print('elapsed={}'.format(thread.elapsed))
print(thread)

03.py execution result


result=33
elapsed=2.0015878677368164
AddThread(name=Thread-1, result=33, elapsed=2.0015878677368164, args=(), kwargs={}, params={})

Commentary (03.py)

Sample (04.py) to join with all threads of the same class

04.py


from commonthread import *


lg = CommonThreadLogger()
lg.setup_basic()


class ShortThread(CommonThread):

    def entry(self, duration):
        lg.debug('start')
        time.sleep(duration)
        lg.debug('end')
        return 'finished'


class LongThread(CommonThread):

    def entry(self, duration):
        lg.debug('start')
        time.sleep(duration)
        lg.debug('end')
        return 'finished'


lg.debug('start')

sth1 = ShortThread(1.0); sth1.name = 'sth1'
sth2 = ShortThread(1.5); sth2.name = 'sth2'

lth1 = LongThread(5.0); lth1.name = 'lth1'
lth2 = LongThread(6.0); lth2.name = 'lth2'

sth1.start()
sth2.start()
lth1.start()
lth2.start()

lg.debug(CommonThread.list_alive())

CommonThread.join_all(type=ShortThread)

lg.debug(CommonThread.list_alive())

CommonThread.join_all()

lg.debug(CommonThread.list_alive())

04.py execution result


MainThread: start
sth1: start
sth2: start
lth1: start
lth2: start
MainThread: [ShortThread(name=sth1, result=None, elapsed=0.0, args=(1.0,), kwargs={}, params={}), ShortThread(name=sth2, result=None, elapsed=0.0, args=(1.5,), kwargs={}, params={}), LongThread(name=lth1, result=None, elapsed=0.0, args=(5.0,), kwargs={}, params={}), LongThread(name=lth2, result=None, elapsed=0.0, args=(6.0,), kwargs={}, params={})]
sth1: end
sth2: end
MainThread: [LongThread(name=lth1, result=None, elapsed=0.0, args=(5.0,), kwargs={}, params={}), LongThread(name=lth2, result=None, elapsed=0.0, args=(6.0,), kwargs={}, params={})]
lth1: end
lth2: end
MainThread: []

Commentary (04.py)

Finally

The features that could not be introduced this time are:

Recommended Posts

I tried using a library (common thread) that makes Python's threading package easier to use
[Git] I tried to make it easier to understand how to use git stash using a concrete example
I tried to touch Python's GUI library "PySimple GUI"
I tried to make a ○ ✕ game using TensorFlow
[Python] Deep Learning: I tried to implement deep learning (DBN, SDA) without using a library.
I tried using the Python library "pykakasi" that can convert kanji to romaji.
I tried to make a translation BOT that works on Discord using googletrans
I tried to draw a configuration diagram using Diagrams
How to use pip, a package management system that is indispensable for using Python
I made a tool that makes it a little easier to create and install a public key.
I tried to automate [a certain task] using Raspberry Pi
I tried to make a stopwatch using tkinter in python
I tried to make a simple text editor using PyQt
I wrote a class that makes it easier to divide by specifying part of speech when using Mecab in python
I tried to make a site that makes it easy to see the update information of Azure
Note that I was addicted to accessing the DB with Python's mysql.connector using a web application.
[Python] I tried to make a simple program that works on the command line using argparse.
I tried to create a server environment that runs on Windows 10
I tried to get a database of horse racing using Pandas
I want to use a wildcard that I want to shell with Python remove
I tried to make a system that fetches only deleted tweets
I tried to make a regular expression of "amount" using Python
I tried to make a regular expression of "time" using Python
I tried to implement anomaly detection using a hidden Markov model
[Python] A memo that I tried to get started with asyncio
I tried to make a regular expression of "date" using Python
I tried to get a list of AMI Names using Boto3
I tried to make a todo application using bottle with python
I made a library that adds docstring to a Python stub file.
[Python] I made a decorator that doesn't seem to have any use.
I tried to implement a blockchain that actually works with about 170 lines
PyPi debut I tried to pip install a library to check Japanese holidays
I won't have a hard time anymore. .. Multi-process using Python's standard library.
I tried to develop a Formatter that outputs Python logs in JSON
How to use hmmlearn, a Python library that realizes hidden Markov models
I tried to understand the decision tree (CART) that makes the classification carefully
[Pyto] I tried to use a smartphone as a flick keyboard for PC
I made a library konoha that switches the tokenizer to a nice feeling
I made a tool that makes decompression a little easier with CLI (Python3)
I tried to perform a cluster analysis of customers using purchasing data
I tried the common story of using Deep Learning to predict the Nikkei 225
I tried to create a sample to access Salesforce using Python and Bottle
I tried to make a skill that Alexa will return as cold
I tried to create a linebot (implementation)
I tried to create a linebot (preparation)
I tried playing a ○ ✕ game using TensorFlow
I tried drawing a line using turtle
How to install a package using a repository
I tried to classify text using TensorFlow
I tried to make a Web API
I tried to understand the learning function of neural networks carefully without using a machine learning library (first half).
I tried using pipenv, so a memo
I tried to predict Covid-19 using Darts
I tried to create a class that can easily serialize Json in Python
I tried to use Java with Termux using Termux Arch but it didn't work
[Python] I tried to make a Shiritori AI that enhances vocabulary through battles
I tried to make a dictionary function that does not distinguish between cases
I tried to make a suspicious person MAP quickly using Geolonia address data
I tried to build a super-resolution method / ESPCN
I tried to build a super-resolution method / SRCNN ①
I tried to synthesize WAV files using Pydub.