Repository navigation
Multiprocessing not compatible with Flet #4283
Copy link
Copy link
Closed
Milestone
Description
Here is an example of the issue that I am finding with multiprocessing. The GUI effectively doubles when Multiprocessing is called. The reason for this is that Python's Multiprocessing calls sys.executable to obtain the Python interpreter to run the new processes/workers. (see comment)
When the Flet application is built, as discussed, sys.executable will by default point to the application executable. Hence, this behaviour will only be observed within applications that have been built using Flet Build, and not Flet Run.. further, PyInstaller seem to have fixed this - so it isn't present in Flet Pack.
Application:
- Basic sort of the same list of numbers, but across multiple workers (processes).
- Using a multiprocessing.Queue() to pass information.
- Running the long running task using page.run_thread()
- Updating the GUI only from the main thread.
Behaviour:
- When running from terminal/ Flet Run the application behaves as expected.
- When running the .app created with Flet Build (using your latest dev build from yday, dev3598), there are two behaviours:
- As soon as the application is launched, another GUI window appears. I believe this is when we create the Multiprocessing.queue()
- When the actual processing starts, a window is created for each worker that is used by multiprocessing.
#main.py
import flet as ft
from flet import Page, Text, ElevatedButton
from multiprocessing import Queue
import numpy as np
from concurrent.futures import ProcessPoolExecutor, as_completed
def sort_sublist(sublist):
"""Sorts a sublist of numbers."""
return sorted(sublist)
def parallel_sort(queue_var):
num_elements = 10_000_000
data = np.random.rand(num_elements).tolist()
number_of_sorts = 20
"""Sorts a list of numbers in parallel."""
with ProcessPoolExecutor(max_workers=10) as executor:
futures = [executor.submit(sort_sublist, data) for _ in range(number_of_sorts)] # Sort the same list x times
for future in as_completed(futures):
queue_var.put(1)
def main(page: Page):
page.title = "Flet Background Task Example"
queue_var = Queue()
text = ft.Text("Init")
def update_text():
completed = 0
while True:
completed += queue_var.get()
text.value = completed
text.update()
def on_click(e):
page.run_thread(parallel_sort,queue_var)
update_text()
page.add(
ElevatedButton("Start Loop", on_click=on_click),
)
page.add(
text
)
if __name__ == "__main__":
multiprocessing.freeze_support()
ft.app(target=main)#requirements.txt
flet==0.25.0.dev3598
numpy
Originally posted by @ap4499 in #4252 (comment)
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
No labels
Type
Projects
- StatusShow more project fields✅ Done
Activity
ap4499 commentedon Oct 31, 2024
I think the reason that Multiprocessing is exhibiting the same issue as subprocess, is the one that you have identified already - the usage of sys.executable, and what that actually is for a Flet application.
set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))https://docs.python.org/3/library/multiprocessing.html
ap4499 commentedon Oct 31, 2024
I suspect all applications that utilise multiprocessing will need the following line as the first line in the if name block.. but I'm unsure whether/if anything is required on the dev side
multiprocessing.freeze_support()ap4499 commentedon Nov 1, 2024
I am using the new dev build that you provided for subprocess, and can confirm that the sys.argv are coming through.
It seems that multiprocessing is indeed passing arguments using sys.argv, and all of them seem to at least contain "multiprocessing" (so I use an IN to filter an IF).
However, I have been unable to use this to get multiprocessing working in the way that I thought it should work.
In the below code, I have moved the import of Flet to be conditional, but even so - when the button is clicked, the GUI appears to duplicate.
Even if Multiprocessing was not getting what it needed, I would expect the behaviour in the below program to be null action. I suspect that multiprocessing may have a separate issue to the GUI duplication, as in the console.log file I note that it gives the following
./multiprocessing/resource_tracker.py:123: UserWarning: resource_tracker: process died unexpectedly, relaunching. Some resources might leak.But I am still puzzled why the GUI duplicates.
Build commands used:
FeodorFitsner commentedon Nov 4, 2024
I don't see
multiprocessingin args. I get this when clicking "Start Loop" button:ap4499 commentedon Nov 5, 2024
I get the same. The IF statement is intended to route any argument containing multiprocessing away from the launching the Flet app or any Flet imports.
In the above, when using sys.argv, any time that "multiprocessing" is found in the args, it routes it away from Flet. Multiprocessing seems to pass further arguments after resource tracker, once it fires off the processes - but all of the arguments it passes have commonality, in that it passes "from multiprocessing".
The below is an example of what I was intending. Whenever "Python" is found within the args (once all joined), we enter the IF. (ofc, using orig_argv instead - as by default we get an extra arg to demonstrate the join behaviour)
FeodorFitsner commentedon Nov 5, 2024
OK, I've played a bit, managed to fix some issues in Flet build template and got multiprocessing "partially" working. Here is my last example:
So, some improvements:
FLET_HIDE_APP_ON_STARTenvironment variable forces all child processes to open with a hidden window - no more GUI in workers.-c from multiprocessing...is a command it passes to a child python interpreter henceexec()in my code.What I can't understand is why it's holding child processes hanging after
parallel_sort()call.If you run the program you'll see that there are two processes with the same name. If you close the window or click "Quit app" it will terminate both the main process and a child process.
However, after clicking "Start Loop" the 3rd process is started (I limited to 1 worker) and then neither closing window nor clicking "Quit app" don't terminate child processes.
Looking at multiprocessing module sources I understand it communicates with child worker processes via pipes (so it passes pipe name/number in
from multiprocessing.resource_tracker import main;main(25)).How to drop child processes? Should you call some dispose/cleanup/release login in your app?
Hope that helps.
ap4499 commentedon Nov 6, 2024
I've tried the above code on both Windows and Mac, and when the app is built, it shows a blank screen on both (even after the initialisation).
The below is my Windows command, in which I clear the cache (I like the proposed change btw), and then build it using the latest Flet.
requirements.txt
In the below code, I have only changed two lines for the purposes of debugging, and I am finding that the application, when run using flet run main.py, the application cannot be exited, in the same way that occurs in your above example. (it doesnt run using Flet build).
Terminal output when clicking the "X" in the Windows native toolbar.
ap4499 commentedon Nov 25, 2024
I am still encountering an issue when the application is built - I cant get it to launch the multiprocess workers.
The above issue where the window would not launch has been resolved by one of the intermediate Flet versions though.
Observed behavior:
Using Flet Run:
Flet Build:
Workaround considered:
Question:
Thanks for the support on this - appreciate all the effort going into this on your side.
FeodorFitsner commentedon Nov 25, 2024
Answering your question: the most of the work to support multiprocessing is done in flet build template project, not Flet package itself, so we could further look into that once 0.25 is released. It's independent work.
ap4499 commentedon Jan 18, 2025
@FeodorFitsner thanks for your response. Would it be possible to look into this again?
Really hoping to use it on my project. I had switched to using an embedded PyInstaller executable to get around the issue, however, unrelated to Flet, GateKeeper is proving hard work with this approach - and long term, it would be preferable for Flet to support Multiprocessing (on MacOS / Win only ofc)
PraiseTheDarkFlo commentedon Jun 19, 2026
Hey, I would also highly appreciate it if multiprocessing support could be introduced. In my application, I am calling external libraries, and without multiprocessing, I currently have no reliable way to terminate those tasks early. Having this feature working natively would be a huge help!
fix: hide the console window of the git version-fallback on Windows
Multiprocessing child interception: run the host binary as a headless…
Desktop multiprocessing support: `PYTHONINSPECT` removal, version-key…