问题
I am writing into a file using android-ndk . So writing in file is taking place using native c code.
It contains some kind of readings that i am putting in using ndk. On click of a button the writing into a file start. And simultaneously i want to read contents of file and use them into another thread for showing up the values as writing operation might continue for 15 sec and user will have to wait for that much time to see the result so i want to show result one by one as soon as i get it into that file.
Is it feasible ,if yes can show me the way how to go about that?
Well i started with it and right nw its how i am doing it ,,
Thread thr1 = new Thread(r1);
Thread thr2 = new Thread(r2);
thr1.start();
thr2.start();
r1 = new Runnable() {
public void run() {
File sdcard= Environment.getExternalStorageDirectory();
nativeFunction(sdcard +"/readings.txt");
//takingReading=false;
readingFile = new File(sdcard +"/readings.txt");
Log.i("length of file", ""+readingFile.length());
}
};
r2 = new Runnable() {
public void run() {
try {
Thread.sleep(3000);
File sdcard= Environment.getExternalStorageDirectory();
readingFile = new File(sdcard +"/readings.txt");
Log.i("length of file", ""+readingFile.length());
} catch (InterruptedException iex) {}
}
};
nativeFunction opens
file= fopen(location,"w+");
This function keeps on writing things in file for around 2 minutes, but i need to continuously get the values entered bye native function so i started 2nd thread but when i check file.length() its always 0.
and when nativefunction write is complete then actual file size comes. So how to get around this problem?
回答1:
This should be possible using pthreads. So you need to spawn 2 threads, one doing the writing and other doing the reading. If you are doing it from the same file, you may run into race conditions, so be careful.
More more info on pthreads, kindly google. It's commonly used by the Linux world.
来源:https://stackoverflow.com/questions/12856215/simultaneously-write-and-read-a-file-from-ndk-in-android