python threading Thread class code example
Example 1: threading python
import threading
import time
def thread_function(name):
print(f"Thread {name}: starting")
time.sleep(2)
print(f"Thread {name}: finishing")
my_thread = threading.Thread(target=thread_function, args=(1,))
my_thread.start()
time.sleep(1)
my_second_thread = threading.Thread(target=thread_function, args=(2,))
my_second_thread.start()
my_second_thread.join()
Example 2: multithreading python
class FakeDatabase:
def __init__(self):
self.value = 0
self._lock = threading.Lock()
def locked_update(self, name):
logging.info("Thread %s: starting update", name)
logging.debug("Thread %s about to lock", name)
with self._lock:
logging.debug("Thread %s has lock", name)
local_copy = self.value
local_copy += 1
time.sleep(0.1)
self.value = local_copy
logging.debug("Thread %s about to release lock", name)
logging.debug("Thread %s after release", name)
logging.info("Thread %s: finishing update", name)