Race condition when running background task

I’ve run into a race condition that causes a hang when running a background task and a progress bar. The sequence is

  1. Start Function
  2. Function has nothing to do or finishes too quickly
  3. Success function is called and showInfo displays a message
  4. Progress Bar is activated.
  5. Because Progress Bar is activated, showInfo cannot be closed
  6. Progress Bar hangs because there is nothing to actually do. The Function has already ended.

Code:

    op = QueryOp(
        parent=mw,
        op=lambda col: batch_get_audio(col),
        success=on_success,
    )

    # Show a progress window
    op.with_progress(label="Fetching Audio").run_in_background()

There’s a reasonable chance the issue is in the context you have not provided. Please provide a minimum full example that we can use to try to reproduce the problem.

This is the shortest code that I could think of. It’s really stupid, but it accurately replicates the problem

def batch_get_audio2(col: Collection):
    return [0, 0]

def on_success(count: tuple) -> None:
    showInfo(f"{count[0]} Meanings Added.\n {count[1]} not found.\n)

 op = QueryOp(
        parent=mw,
        op=lambda col: batch_get_audio2(col),
        success=on_success,
    )

    # Show a progress window
    op.with_progress(label="Fetching Audio").run_in_background()

Could you please provide a full example that is valid Python and that I can drop directly into the add-on folder?

@dae Here is a full example that I tested in Anki to reproduce the error.

from aqt import mw
from aqt.utils import showInfo
from anki.collection import Collection
from aqt.operations import QueryOp
from aqt.qt import *

def batch_get_audio2(col: Collection):
    return [0, 0]

def on_success(count: tuple) -> None:
    showInfo(f"{count[0]} Meanings Added.\n {count[1]} not found.\n")

def batch_download() -> None:

    op = QueryOp(
            parent=mw,
            op=lambda col: batch_get_audio2(col),
            success=on_success,
        )

    # Show a progress window
    op.with_progress(label="Fetching Audio").run_in_background()




# Add the Item to the Menu
action = QAction("Race Tester", mw)
# set it to call testFunction when it's clicked
qconnect(action.triggered, batch_download)
# and add it to the tools menu


mw.form.menuTools.addAction(action)
4 Likes

I can confirm the error happens in 2.1.50, but it seems to be fixed in latest master

2 Likes

Probably with this, which finishes the progress before calling success:

3 Likes

This fix is in 2.1.52, which was released today.

1 Like

I can confirm that this is fixed in 2.1.52. Thanks!