Home | History | Annotate | Download | only in native
      1 /*
      2  * Copyright (C) 2010 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #ifndef ASYNCHRONOUS_CLOSE_MONITOR_H_included
     18 #define ASYNCHRONOUS_CLOSE_MONITOR_H_included
     19 
     20 #include "ScopedPthreadMutexLock.h"
     21 #include <pthread.h>
     22 
     23 /**
     24  * AsynchronousCloseMonitor helps implement Java's asynchronous close semantics.
     25  *
     26  * AsynchronousCloseMonitor::init must be called before anything else.
     27  *
     28  * Every blocking I/O operation must be surrounded by an AsynchronousCloseMonitor
     29  * instance. For example:
     30  *
     31  *   {
     32  *     AsynchronousCloseMonitor monitor(fd);
     33  *     byteCount = ::read(fd, buf, sizeof(buf));
     34  *   }
     35  *
     36  * To interrupt all threads currently blocked on file descriptor 'fd', call signalBlockedThreads:
     37  *
     38  *   AsynchronousCloseMonitor::signalBlockedThreads(fd);
     39  *
     40  * To test to see if the interruption was due to the signalBlockedThreads call:
     41  *
     42  *   monitor.wasSignaled();
     43  */
     44 class AsynchronousCloseMonitor {
     45 public:
     46     AsynchronousCloseMonitor(int fd);
     47     ~AsynchronousCloseMonitor();
     48     bool wasSignaled() const;
     49 
     50     static void init();
     51 
     52     static void signalBlockedThreads(int fd);
     53 
     54 private:
     55     AsynchronousCloseMonitor* mPrev;
     56     AsynchronousCloseMonitor* mNext;
     57     pthread_t mThread;
     58     int mFd;
     59     bool mSignaled;
     60 
     61     // Disallow copy and assignment.
     62     AsynchronousCloseMonitor(const AsynchronousCloseMonitor&);
     63     void operator=(const AsynchronousCloseMonitor&);
     64 };
     65 
     66 #endif  // ASYNCHRONOUS_CLOSE_MONITOR_H_included
     67