Skip to content

How to use multithreading in flask #2961

Description

@tsiens
          > I think figured out what causes it to break. If you run flask with `threaded=False`, then it works. I think that indicates that the request is being handled by a new thread, but the new thread is no longer using the correct class loader. That is one of the thing's that's cautioned about in https://developer.android.com/training/articles/perf-jni#faq_FindClass:

You can get into trouble if you create a thread yourself (perhaps by calling pthread_create and then attaching it with AttachCurrentThread). Now there are no stack frames from your application. If you call FindClass from this thread, the JavaVM will start in the "system" class loader instead of the one associated with your application, so attempts to find app-specific classes will fail.

This seems to be exactly what's happening. A native thread is being created to handle each request in werkzeug. This new thread is attached to the JVM via a pyjnius monkey patch, but since it has a new stack frame you end up using the Java system class loader. I actually think this likely affects sdl2 apps as well since I don't think there's anything SDL can do to avoid this situation.

So, I think there are basically 2 solutions:

  1. Document that if you're using threads in your app, you have to resolve app classes before you run them.
  2. Resolve the classes in the JNI_OnLoad function. I think this is doable except that the build time constructed service classes would be tricky to handle. This also wouldn't affect the sdl2 bootstrap case since p4a uses it's JNI handling code.

For now I'm just going to make a PR that makes flask run non-threaded in the test app since it specifically tries to delay resolving the classes.

However, I still need to use Multithreading in the Flask,I am trying to use

from android.runnable import Runnable
Runnable(main)(*args, **kwargs)

But when the request calls the Runnable, the entire app will freeze and unable to perform any operation,Until the Runnableis completed
What should I do?

Originally posted by @tsiens in #2533 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions