#!/usr/bin/python # -*- coding: utf-8 -*- import logging import time import threading #import stacktracer as strace db_lock = threading.RLock() class MyDatabase(object): # Python 2 def __unicode__(self): time.sleep(8) with db_lock: print("I will never have the lock") return "42" # Python 3 def __str__(self): time.sleep(8) with db_lock: print("I will never have the lock") return "42" def log_pid(self): with db_lock: time.sleep(2) logging.warning(u"my_db pid is: %s", u"1234") my_db = MyDatabase() def first_thread(): print("1st started!") logging.warning(u"My slow pid is: %s", my_db) print("1st finished") return 0 def second_thread(): print("2nd started!") my_db.log_pid() print("2nd finished") return 0 def main(): print("Start") # log on the console logging.basicConfig(level = logging.DEBUG) th1 = threading.Thread(target=first_thread, name='first-thread') th1.start() th2 = threading.Thread(target=second_thread, name='second-thread') th2.start() print("All threads launched") th1.join() th2.join() print("End") if __name__ == "__main__": #strace.trace_start("testLOCKtrace.txt", interval=10, auto=True) main() #strace.trace_stop()