How to use “threading” in python in an unblocking way?

I have a complete “working” python code which is supposed to contain two threads which run simultaneously, which populate some lists in a dict, and when the user presses CRTL-C these two threads should be stopped and some output from both threads should be written to a file:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>import sys
import time
import threading
import signal
from functools import partial
messages = {}
lock = threading.Lock()
class Handler:
def __init__(self, port):
self.port = port
def run(self):
while True:
time.sleep(1)
with lock:
messages[self.port].append(time.time())
def signal_handler(filename, sig, frame):
with lock:
with open(filename, "w") as fileout:
json.dump(messages, fileout)
sys.exit(0)
output = "test.out"
signal.signal(signal.SIGINT, partial(signal_handler, output))
for port in [1,2]:
messages[port] = []
handler = Handler(port)
print("debug1")
t = threading.Thread(target=handler.run())
print("debug2")
t.daemon = True
t.start()
threads.append(t)
# Keep the main thread running, waiting for CTRL-C
try:
while True:
pass
except KeyboardInterrupt:
signal_handler(output, signal.SIGINT, None)
</code>
<code>import sys import time import threading import signal from functools import partial messages = {} lock = threading.Lock() class Handler: def __init__(self, port): self.port = port def run(self): while True: time.sleep(1) with lock: messages[self.port].append(time.time()) def signal_handler(filename, sig, frame): with lock: with open(filename, "w") as fileout: json.dump(messages, fileout) sys.exit(0) output = "test.out" signal.signal(signal.SIGINT, partial(signal_handler, output)) for port in [1,2]: messages[port] = [] handler = Handler(port) print("debug1") t = threading.Thread(target=handler.run()) print("debug2") t.daemon = True t.start() threads.append(t) # Keep the main thread running, waiting for CTRL-C try: while True: pass except KeyboardInterrupt: signal_handler(output, signal.SIGINT, None) </code>
import sys
import time
import threading
import signal
from functools import partial

messages = {}
lock = threading.Lock()

class Handler:
    def __init__(self, port):
        self.port = port

    def run(self):
        while True:
            time.sleep(1)
            with lock:
                messages[self.port].append(time.time())


def signal_handler(filename, sig, frame):
    with lock:
        with open(filename, "w") as fileout:
                json.dump(messages, fileout)
    sys.exit(0)


output = "test.out"
signal.signal(signal.SIGINT, partial(signal_handler, output))
for port in [1,2]:
    messages[port] = []
    handler = Handler(port)
    print("debug1")
    t = threading.Thread(target=handler.run())
    print("debug2")
    t.daemon = True
    t.start()
    threads.append(t)

# Keep the main thread running, waiting for CTRL-C
try:
    while True:
        pass
except KeyboardInterrupt:
    signal_handler(output, signal.SIGINT, None)

However, this code blocks execution after the first debug1 has been printed. How to “unblock” this line so the two threads are started until the user presses CRTL-C (and the output is saved to a file)?

…The above code is just a template of a more complicated code that actually does something useful…

Apart from various typos (forgotten import json and threads=[]) the main problem is in t = threading.Thread(target=handler.run()).

The target parameter is expected to be a function object, not the result of the call of that function. Here this code immediately calls the never ending function to assign its never coming result to t, actually blocking the main program.

The solution is just to remove the parens:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>t = threading.Thread(target=handler.run)
</code>
<code>t = threading.Thread(target=handler.run) </code>
t = threading.Thread(target=handler.run)

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật