I'm trying to implement a native shared library(.so) for the Android system. Naturally, there are some code blocks that need to be thread-safe.
I found out here that pthreads locks, mutexes, or condition variables are not supported.
I'd like to know what is usually used at the library level to achieve thread-safety?
Thread safe: Implementation is guaranteed to be free of race conditions when accessed by multiple threads simultaneously. Conditionally safe: Different threads can access different objects simultaneously, and access to shared data is protected from race conditions.
By design, Android View objects are not thread-safe. An app is expected to create, use, and destroy UI objects, all on the main thread. If you try to modify or even reference a UI object in a thread other than the main thread, the result can be exceptions, silent failures, crashes, and other undefined misbehavior.
When an application is launched in Android, it creates the primary thread of execution, referred to as the “main” thread. Most thread is liable for dispatching events to the acceptable interface widgets also as communicating with components from the Android UI toolkit.
How this can be achieves depends on whether you just want it to be thread safe when accessed by Java level threads, or you need to synchronize native threads with Java threads.
There are two ways to synchronize only Java level threads:
1.The easiest way is to add the synchronized keyword to the native methods that be accessed by multiple thread, i.e.
public native synchronized int sharedAccess();
2.Synchronization from the native side:
(*env)->MonitorEnter(env, obj);
... /* synchronized block */
(*env)->MonitorExit(env, obj);
Refer here on how to synchronize native threads with Java threads
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With