Skip to main content

AioThreading

A Fork of aiomultiprocess built around threading for enhancing performance whenever processes can't be used

PyPI version PyPI - Downloads License: MIT code style

After 6 years of waiting, it finally exists. This library was inspired by the amazing work of Amyreese and the other contributors of aiomultiprocess as well as the original ThreadPoolExecutor apart of the python standard library, originally my plan was to write my own threadpool that could do this and many different versions were attempted by me over the past 2 years which all of them had problems of their own such as workers failing to exit properly and more. Eventlually I had decided to fork this branch off instead with the goal of implementing this feature that I have long wanted which was asyncio but with threads. There are some occasions where this can be useful such as running a discord bot and http server at the same time when you only have so many computer cpu cores to work with. This can come in handy when you do not need to spawn or fork in a process but at the same time you need to reduce the main loop's overall workload which can be helpful if your goal is to send multiple http requests for instance as sometimes some things can block that you didn't indend or expect to be blocked that shouldn't, aiothreading attempts solve these problems and more of them. The best part of all, no more having to ask on sites like stackoverflow about how to run a thread with an asyncio eventloop, I have just solved that problem.

Installation

pip install aiothreading

Examples

Threads

from aiothreading import Thread, Worker
from aiohttp import request


async def do_request(link:str) -> str:
    async with request("GET", link) as resp:
        # get data before closing
        data = await resp.json()
    print(f"Your IP address is: {data['origin']}") 
    return data['origin']

async def main():
    thread = Thread(target=do_request, args="https://httpbin.org/ip")
    thread.start()
    # to join the thread you can either await it or join it 
    await thread.join()

    # This will also work...
    await thread



async def worker():
    # Wokers have the ability to return items after execution completes...
    # NOTE: Workers will be renamed to ThreadWorker in a future update so aiomutliprocess doesn't collide with this class object
    worker = Worker(target=do_request, args="https://httpbin.org/ip")
    worker.start()

    await worker.join()
    ip = worker.result
    print(ip)

Integrating with Uvloop or Winloop

A Faster eventloop such as uvloop or winloop have been programmed to have better performance than python's stdlib asyncio The ThreadPool and Threads and Workers can be used to make your threads run a bit faster.

# Import uvloop if your not on windows
import platform 
if platform.platform == "Windows":
    import winloop as uvloop
else:
    import uvloop

from aiothreading import Thread, Worker, ThreadPool

await Thread(
    target=some_coro, loop_initializer=uvloop.new_event_loop
)
result = await Worker(
    target=other_coro, loop_initializer=uvloop.new_event_loop
)

async with ThreadPool(loop_initalizer=uvloop.new_event_loop) as pool:
    ...

ThreadPool

ThreadPool is a renamed version of aiomultiprocess.Pool so that if you were to import and use both of them at the same time for whatever reasons the names don't overlap

# In case you need to use both of them at the same time
from aiomultiprocess import Pool
from aiothreading import ThreadPool

This example was taken from aiomultiprocess

from asyncio import gather
from aiothreading import ThreadPool

async def get(url):
    async with request("GET", url) as response:
        return await response.text("utf-8")

# the threadpool works the same as aiomultiprocess.Pool 
async with ThreadPool() as pool:
    a, b, c, d = gather(
        pool.apply(get, "https://github.com"),
        pool.apply(get, "https://noswap.com"),
        pool.apply(get, "https://omnilib.dev"),
        pool.apply(get, "https://github.com/Vizonex")
    )

When to Use Aiothreading Over AioMultiprocessing

  • If aiomutliprocess seems like too much try this library.

  • when you need something that is more recently maintained.

  • High task consumption over a single loop on a lower-end device

  • Networking or loading takes longer than usual in cases such as webscraping over the Tor Network

  • Your writing an application via executable such as compiling with pyinstaller which has been notorious for not working with multiprocessing but you don't want something that will wind up acting too slow

  • When you need to run something such as a discord bot and http server over the same process examples of when you would do this would be when running a health check on the discord bot.

  • When you don't need something fancy or grandiose.

  • Your working with a potato operating system, rasberrypi, libre-computer, etc...

  • When you need to combine aiomultiprocess library with this one.

  • Low CPU overall

If none of these fit your criteria I highly encourage you to use the aiomultiprocessing library, it's way faster and has smarter exiting techniques.

TODOS

  • add aiologic to fix responsiveness of some threads to fix speeds and performance.
  • Youtube Video about how to use

Metadata

Release files for aiothreading 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aiothreading 0.3.0
File Size Uploaded Provenance Actions
aiothreading-0.3.0.tar.gz 14.2 kB Without provenance Details for aiothreading-0.3.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for aiothreading 0.3.0
File Interpreter ABI Platform Actions
aiothreading-0.3.0-py3-none-any.whl Python 3 none any Details for aiothreading-0.3.0-py3-none-any.whl

Total release size: 25.7 kB

Release files / aiothreading-0.3.0.tar.gz

Download URL aiothreading-0.3.0.tar.gz
Size 14.2 kB
Tags Source
SHA-256 checksum
How to use checksums
7485b15ffa20ba3f5762d50e9c02fbdd6cda147b2fed37a2e72b097cc865140c
BLAKE2b-256 checksum
How to use checksums
d485acb8002fc1993b44b8849f8d92d0d1216622afce6d059a3263027fa6f9b4
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.13

Release files / aiothreading-0.3.0-py3-none-any.whl

Download URL aiothreading-0.3.0-py3-none-any.whl
Size 11.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fae1b8ac70cc06eb5d62b6856574d81c881226c63f016cd4e4023df6808a9fda
BLAKE2b-256 checksum
How to use checksums
31d007ffd92fa0188986903a66baae2092edabb102a13b6dac3a1899e0eb8b34
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.1.0 CPython/3.13.13

Security for aiothreading 0.3.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page