Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safety in Android libraries

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?

like image 871
sundie Avatar asked Sep 10 '14 21:09

sundie


People also ask

What are thread-safe libraries?

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.

What is thread-safe in Android?

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.

How are threads managed in Android?

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.


1 Answers

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

like image 106
Kai Avatar answered Sep 21 '22 13:09

Kai