Skip to content

Improve the threading model for lifecycle events #10

@SpexGuy

Description

@SpexGuy

Lifecycle events (onStart, onPause, onNativeWindowDestroyed, etc) come from threads that are disjoint from the main "background" thread, which runs independently. The way synchronization between these threads is done in the example is simply with a lock. This has two problems:

  1. If the lock is dropped and then taken again quickly by the main thread, waiting event threads may be starved out. Mutexes on Android are not "fair", and will not necessarily prioritize threads that have been waiting longer. This is unlikely to deadlock the application, but could cause a few extra frames of latency that are unnecessary.
  2. For calls like onNativeWindowDestroyed, it is important that the background thread does not continue to use the window after this function returns. This means that if the bg thread has access to the window, the event thread must pause and wait for the background thread to acknowledge the event before returning.

The "official" native app glue in the apk has a nicer model that might be worth taking a look at, where events are put into a queue and then the event thread waits for a signal from the background thread that the event has been processed. You can find it in ndk/sources/android/native_app_glue/android_native_app_glue.c (apache 2.0 licensed).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions