Showing posts with label thread. Show all posts
Showing posts with label thread. Show all posts

Thursday, June 11, 2015

Thread safety

Before I start with thread safety, evolving design, if something can be improved don't be lazy.
Now I remembered that GCC supports 128 bit integers and that Fibonacci numbers can be calculated up to forty digits. There is problem with printing those 128 bit integers but somebody already offered utility function to convert them to string, that was Perkins . I only added zero case to his solution.


Now we can go up to 186th Fibonacci number without overflow.

Threads

There is few buzz words which people are using in job ads, related to threads, but usually they fail to define them. For example multithreading, concurrency, thread safety, reentrant function and similar.
What is reentrant function or thread safe function? That would be such function that does not use statically allocated or global variables and result depends only on input arguments. For example:


is not reentrant or threadsafe. If more than one thread calls that function in the same time, that is concurrency, it will produce unpredictable result. Even if it is called sequentially result will be influenced by previous calls, possibly from different thread. We are on Linux and we are using POSIX threads. So, here is example where two threads are calling nonreentrant function:


To compile it I used:

gcc -o notreentrant -g -gdwarf-2 notreentrant.c -pthread

That -gdwarf-2 story is distraction, I am using gcc version 4.9.2 built from source on old Mint based on Ubuntu 12.04 and new gcc outputs by default debug info which gdb doesn’t understand. If you just built new gcc and gdb doesn't work as expected, that is cure. Linker switch -pthread is required.
Example output from execution looks like this:

thread 1 call 1 = 2, expecting 2
thread 1 call 2 = 7, expecting 4
thread 1 call 3 = 9, expecting 6
thread 1 call 4 = 11, expecting 8
thread 2 call 1 = 5, expecting 3
thread 2 call 2 = 14, expecting 6
thread 2 call 3 = 17, expecting 9
thread 2 call 4 = 20, expecting 12
thread 1 exit code 1
thread 2 exit code 2


How do we remedy that? We make increase reentrant or thread safe:


We requested thread local storage, available since kernel 2.6 and supported by gcc 3.3 and higher. When thread terminates and goes out of scope, local thread storage does to. We could make function reentrant via using thread specific data, but that is much more code, maybe next time.

Monday, February 25, 2013

C++ and pthreads on Linux

If one wants to use NDK and that is JNI on Android, sooner or later he will run into threading on Linux, yes Android is Linux. Pthreads is short for POSIX threads where POSIX is Portable Operating System Interface. Since they are portable they will work on Unix, Linux, FreeBSD, Mac and so on. Pthread is defined in pthread.h and represents set of C functions, structs and defs, to discover where it is you can execute from terminal:

$ locate pthread.h

If you have NDK installed you will see that pthread.h is part of it and that arch-arm version is significantly smaller than /usr/include/pthread.h one. To cut long story short we can do Hello World and see how it looks like:


It is quite simple, we declare thread function, thread itself and then we create thread and pass function pointer and argument in pthread_create. Later we join and exit. To compile it we do:

g++ -pthread simple.cpp -o simple

That -pthread switch is linking instruction. Now cout is not thread safe and we may want to use mutex to make printing to standard output safe.


Now one can go and wrap pthread or mutex in class and make it easier to use. Only we need to be careful with that function pointer in pthread_create, that is C function and passing class method won’t work without some additional coding and static casting.
Finally we will take a look at pthread_key_create, which is recommended by Android documentation. Its signature is:

int pthread_key_create(pthread_key_t *key, void (*destructor)(void *));

That "destructor" should free resources taken by key when thread exits. Key itself is global variable but on thread level, sort of locally global. So here is example:


When you build it and execute it you will see that cout is not thread safe. If you want to wrap pthread in class, very good reading is Implementation and Usage of a Thread Pool based on POSIX Threads by Ronald Kriemann, sorry do not have link for it. Beside mutex, there are are condition variables and semaphores to help with concurrency issues. If you are going to fork process you may want to use System V semaphores instead of pthread semaphores. Finally for any serious implementation of pthread_key_create you need to look at pthread_once_t.

Saturday, October 27, 2012

Tutorial part 3

In this part we are going to take a look at AsyncTask which is light-weight framework intended to save programmers from concurrency traps and handling of Java threads.

AsyncTask

Most important thing is AsyncTask is intended to be used on UI thread, so do not try to use it elsewhere. Signature is android.os.AsyncTask and you can use them or ignore them and replace unused ones with Void. If you are planning to pass array of strings as parameters and not use progress or result than it becomes android.os.AsyncTask.
There are four commonly used and overridden methods:

protected void onPreExecute ()
protected abstract Result doInBackground (Params... params)
protected void onProgressUpdate (Progress... values)
protected void onPostExecute (Result result)


obviously only doInBacground is compulsory to override and that is only one which is not executing on UI thread. Typical implementation looks like this:

private class FetchItemsTask extends AsyncTask {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog.setMessage("Downloading. Please wait...");
        progressDialog.show();
    }
    @Override
    protected Void doInBackground(Void... params) {
        do some heavy I/O work here
        return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        pass to UI result of work here
        progressDialog.dismiss();
    }
}


Usually it is declared as inner class inside Activity and we have instance of ProgressDialog accessible.
It is not full size threading framework, it should be used as suggested to do lengthy I/O operations. That lengthy is few seconds not few minutes. So good candidate for downloading image from Internet or pulling data from DB. Very good idea here is to go to your Android SDK Manager and to download source code and see how implementation of AsyncTask looks like. Equally good idea is to place logging at every method and log ID of current thread, so that we can be sure where is what executed.
If we take a look at my example in git://github.com/FBulovic/grumpyoldprogrammer.git we will see that my BroadcastReceiver contains  AsyncTask. Knowing that  AsyncTask can bi instantiated only from UI thread we can conclude that  BroadcastReceiver is also executed on UI thread. That was nice intro to CursorAdapter and ContentProvider where execution happens outside of UI thread but they need to communicate with UI thread and that may course some problems here and there. Especially you want to access SQLite DB directly without using ContentProvider.
Next part of this tutorial will follow, soon.