2
votes

I am using the assertion in a multithreaded environment to help me catch early bugs. But it turns out that when assertion failed, python3.7 just terminates silently without printing the error message that I want to see. Thanks for helping in advance.

Here is the sample code:

from concurrent.futures import ThreadPoolExecutor
import threading
import random
from time import sleep
def task():
    assert False, "no assertion output, why?"
    print("Executing our Task")
    sleep(5)
    result = 0
    i = 0
    for i in range(10):
        result = result + i
    print("I: {}".format(result))
    print("Task Executed {}".format(threading.current_thread()))

if __name__ == '__main__':
    executor = ThreadPoolExecutor(max_workers=3)
    task1 = executor.submit(task,1)
    task2 = executor.submit(task,1)
    #task(), directly calling and the assertion failure message will be printed out.

I ran it using the command python3.7 test.py

I think I used python assertion in a wrong way because I assume it to be the assert function in c++. If I change the assertion to throwing an exception, the above code does not print too. Am I supposed to catch the exception?

BTW, directly calling it, and the assertion failure message will be shown though.

1
Does the assertion message print if you just call the task function directly? - Henry Woody
assert will check if the value is true, for your function to execute you need to set your assert to True instead of False. - Simbarashe Timothy Motsi
@HenryWoody yes, directly calling it and I get the error message. If I put it in the threadpool, I need to try and except to catch it in order to print, otherwise it crashes silently and I can't use to to detect bugs. - Han XIAO
@SimbarasheTimothyMotsi Thanks. For this example, I am just triggering the assertion failure in order to see the whether the error message be printed out or not. - Han XIAO
@HanXIAO did you try putting the output message in brackets? assert False, ("no assertion output, why?") - Simbarashe Timothy Motsi

1 Answers

3
votes

The problem is that you are retrieving the futures (assigning the return values to task1 and task2), but doing nothing with them. Try something like this.

for future in futures.as_completed([task1, task2]):
    if future.exception() is not None
        # Process the results here.

This will remove the race you currently have.