// // mp::fiber // // Copyright (C) 2008 FURUHASHI Sadayuki // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #ifndef MP_FIBER_H__ #define MP_FIBER_H__ #include "mp/event.h" #include "mp/fdnotify.h" #include "mp/exception.h" #include "mp/fiber/config.h" #include #include namespace mp { class fiber { public: static void initialize(); static void destroy(); ~fiber(); class handler; private: class impl; public: class handler { public: //! Constructor. /*! void IMPL::operator() () have to be implemented. */ template handler(IMPL* pimpl); virtual ~handler(); public: bool exited() { return context.exited(); } bool failed() { return context.failed(); } protected: friend class fiber::impl; int current_fd; short current_event; coro context; private: std::vector waited; private: handler(); handler(const handler&); }; public: //! Start event loop. static void run(); //! Stop event loop. /*! This function is async-signal-safe. */ static void end(); //! Add event handler /*! * Add new `routine' to be called when `fd' satisfied `event'. * Don't add same handler more than two times. * @param fd file descriptor to watch * @param event EV_READ, EV_WRITE or EV_READ|EV_WRITE * @param routine event handler */ static void add_handler(int fd, short event, handler& routine); //! Suspend current handler's routine until `fd' satisfies `event'. static void yield(int fd, short event); //! Suspend current handler's routine until waked by wake() function. static void suspend(); //! Suspend current handler's routine until `target' ends. static void join(handler& target); //! Return current handler static handler& current(); //! Resume suspended handler's routine. /*! This function is thread-safe unlike other functions. */ static void wake(handler& target); //! Interrupt event wait. /*! This function is thread-safe and async-signal-safe. */ static void interrupt(); static bool test(int fd); private: static std::auto_ptr s_instance; static impl& instance(); fiber(); fiber(const fiber&); }; } // namespace mp #include "mp/fiber_impl.h" #endif /* mp/fiber.h */