マルチスレッド コードは、リソース (ファイル システムなど) に非同期的にアクセスします。
これを実現するために、条件変数を使用します。FileSystem
が次のようなインターフェースであるとします。
class FileSystem {
// sends a read request to the fileSystem
read(String fileName) {
// ...
// upon completion, execute a callback
callback(returnCode, buffer);
}
}
にアクセスするアプリケーションができましたFileSystem
。readFile()
メソッドを介して複数の読み取りを発行できるとします。オペレーションは、渡されたバイト バッファにデータを書き込む必要があります。
// constructor
public Test() {
FileSystem disk = ...
boolean readReady = ...
Lock lock = ...
Condition responseReady = lock.newCondition();
}
// the read file method in quesiton
public void readFile(String file) {
try {
lock.lock(); // lets imagine this operation needs a lock
// this operation may take a while to complete;
// but the method should return immediately
disk.read(file);
while (!readReady) { // <<< THIS
responseReady.awaitUninterruptibly();
}
}
finally {
lock.unlock();
}
}
public void callback(int returnCode, byte[] buffer) {
// other code snipped...
readReady = true; // <<< AND THIS
responseReady.signal();
}
これは条件変数を使用する正しい方法ですか? readFile()
すぐに戻りますか?
(読み取りにロックを使用するのはばかげていることは知っていますが、ファイルへの書き込みもオプションです。)