DEV Community

Rowida
Rowida

Posted on • Edited on

5 2 1 1 1

Notes on Thread and threading module in python

This post encompasses some notes about thread and
Threading module in python, that I used as a quick recap.

What is Thread.

Thread Is a basic unit of CPU Utilization, the smallest unit of processing that can be performed in OS and an entity within a process. One process can have Multiple threads.

What thread contains?

It contains specific information in a Thread Control Block (TCB) such as :

  • Thread ID which is assign to every new thread.

  • Stack pointer that contains the local variables under thread’s scope.

  • Program counter Or Register that contains the address of the current instruction being executed by the Thread.

  • Parent Process Pointer to point to Process control block
    (PCB) of the parent process that this thread lives on.

Threading module provides a very simple and intuitive API for implementing multiple threads. Thread in this module encapsulates threads and provide an interface to work with them.

Python has a complicated relationship with threading thanks to its GIL,

To create a new thread is by calling threading.Thread


from threading import Thread

def foo():
    print("Hola Hola")

f1 = Thread(target = foo)
# the thread will never be executed unless `start` is called
f1.start()
Enter fullscreen mode Exit fullscreen mode

Note Start will run and terminated. Calling thread_name.start again will cause a RuntimeError

You can find the code in the following repository, It's a chapter within a repository for the book Python for professional Book repo.

To Read:

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more