Hi!
I have a question regarding the use of fflush(NULL) from inside native code that are called by different Java threads. I have two different Java threads: the first one calls a native C function called updateBitmap that reads a pattern file containing geometries. The function reads these and updates a bitmap containing a graphical representation of the file. It checks an update variable to see if it, using a Java callback method (setBitmap), shall update the bitmap. This variable is set by the other thread, the screen updater. This other thread informs the first one, using this update variable, that it is time to update the bitmap so the screen can display the currently read file content. Some "pseudocode" is displayed below.
Because I do not know any way to debug a JNI application I have to use printf() statements when trying to debug my application. And there I used fflush(NULL) to flush all buffers so that printf:s were not buffered. But when I started using fflush(NULL) it seems as if the parsing code stopped working. I have not written that part myself, but in single threaded mode it worked ok even with the fflush(NULL) but in multithreaded mode the parsing and update failed. If fflush(NULL) was replaced with fflush(stdout) to just flush the stdout streams it seems to work fine. Does this seem strange, i.e. there is problably a bug in the C library functions, or is there a logical explanation?
So my question is, can fflush(NULL) from multiple Java threads using native functions be a problem. What can go wrong? Do I have to add some compile options, when making my library (.so) file to make it "thread safe", i.e. that the code is to be run using multiple threads.
Here is the "pseudocode":
------------------------------------
Thread-1
------------
In Java
----------
{
// Start the parsing and update of the bitmap.
updateBitmap(...); // Native C call.
// Now the parsing and update of the bitmap is finished.
}
// Bitmap update callback method, called from inside the C part.
setBitmap(int[] bitmap) {
copy the C bitmap to the Java bitmap;
}
In C
-----
// updateBitmap
updateBitmap(...) {
while (there are geometries left in pattern file) {
update the bitmap.
print outs
fflush(NULL);
// Check if the Java bitmap is to be updated, that is if the Java part has requested that.
if (update) {
setBitmap(bitmap); // call the bitmap update callback method (part of Java).
}
}
}
Thread-2
-------------
// update screen.
updateScreen() {
while (still reading pattern file) {
Thread.sleep(time);
update(); // Native function call that informs updateBitmap that it is time to update bitmap.
update screen graphics using bitmap that updateBitmap has updated using setBitmap.
}
}
Native update method.
update() {
sets the update variable.
print outs;
fflush(NULL);
}
Best regards
Lars