Friday, December 30, 2011

Missing pthread_mutex_timedlock on Android

I stumbled upon a problem today that the pthread_mutex_timedlock function definition is missing on Android, though it's declared in the pthread.h.
The first thought was to implement it as a loop with a call to pthread_mutex_trylock and some sleep until we are able to get the lock or until the timeout happens, felt a bit awkward.

I took a look a the Mono for Android source code and that's exactly what they do there (./mono/io-layer/mono-mutex.c), so go figure, looks like this solution might not be that bad after all.


Here is how it's implemented in Mono for example:
int
pthread_mutex_timedlock (pthread_mutex_t *mutex, CONST_NEEDED struct timespec *timeout)
{
 struct timeval timenow;
 struct timespec sleepytime;
 int retcode;
 
 /* This is just to avoid a completely busy wait */
 sleepytime.tv_sec = 0;
 sleepytime.tv_nsec = 10000000; /* 10ms */
 
 while ((retcode = pthread_mutex_trylock (mutex)) == EBUSY) {
  gettimeofday (&timenow, NULL);
  
  if (timenow.tv_sec >= timeout->tv_sec &&
      (timenow.tv_usec * 1000) >= timeout->tv_nsec) {
   return ETIMEDOUT;
  }
  
  nanosleep (&sleepytime, NULL);
 }
 
 return retcode;
}

Wednesday, December 28, 2011

... из жизни


Сегодня на обеде видел одного папашу с маленьким ребёнком (меньше года). Дядька это болтал с двумя тётками которые сидели с ним за столом, пил большую банку Monster Energy Drink и тряс коленкой на которой сидел ребёнок ну наверное с частотой не меньше 300 ударов в минуту, так что казалось что у ребёнка либо голова отвалится, либо будет обширное сотрясение мозга.
"Энергетики" это вам не игрушка....



Nouns vs Verbs

Stumbled upon this post today,  it's almost 6 years old, but I haven't seen it before and enjoyed reading it quite a bit:

Execution in the Kingdom of Nouns

Hope you like it too.

Monday, December 26, 2011

Говорят дети


Саша просит поиграться на таблете:
- Хочу игру где убивают злых поросят ...

(Angry Birds)

Friday, December 23, 2011

How to setup Eclipse for debugging with Android NDK


Just wanted to bookmark couple of useful links on how to setup Eclipse IDE for debugging with NDK. Sometimes it might be more convenient than doing ndk-gdb from terminal, that I still didn't quite get used to yet. It took a bit of time and few tries to get things going. I had some problems with symbols loading and matching, and finally succeeded. Anyways if stuck check comments to these articles. 
  1. Setup your project to be a mixed Java, C, and C++ project:
  2. Setup your project to enable debugging:

Thursday, December 08, 2011

Хочу как у мусорщика


По дороге в детский садик, Саша позади в детском сиденье возится с кепкой.
Я: -Саша ты что там с кепкой делаешь.
Саша: -Хочу как у мусорщика.....

... и одевает кепку набок ...

... а ведь было же время когда завораживали мусорные машины с автоматическими подъёмниками, строительная техника и т.д. ... поменялись с возрастом интересы и приоритеты как-то ....

Friday, December 02, 2011

Android NDK logging

Just wanted to share the snipped that often used in the different Android native projects.
The following are some useful macros for logging with NDK.

#include<android/log.h>

#define LOGD(LOG_TAG, ...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__)
#define LOGV(LOG_TAG, ...) __android_log_print(ANDROID_LOG_VERBOSE, LOG_TAG, __VA_ARGS__)
#define LOGE(LOG_TAG, ...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)

You can define more as needed just take a look at the android/log.h header file for all available priority values.
Then I would usually define log TAG:
#define LOG_TAG "MyModule"

and use the macros like this:
LOGD(LOG_TAG, "my val: %s", val);


fopen with native library on Android

If you develop an Android application with some native C/C++ layer (NDK) and 
try to open the file from it by doing FILE *pFile = fopen ("myfile.txt" ,"w");
the fopen call will fail.

The reason is that the current working directory for you application is the root of file system '/' and naturally your application doesn't have access to it.

In order to fix this problem you have to pass the full path for the file to fopen call.
One way to do this is to pass the base path to your application data folder where your application has read/write permissions. For example you can use the Context API getFilesDir().getAbsolutePath()
and pass the result to the native function call.
This particular API resolves currently into something like: "/data/data/[app package]/files/"

In your native code then the fopen call should succeed with 
FILE *pFile = fopen ("/data/data/[app package]/files/myfile.txt" ,"w"); 

Hope this was helpful.