David Reiss | 791a57f | 2008-06-10 22:54:56 +0000 | [diff] [blame^] | 1 | // Copyright (c) 2008- Facebook |
| 2 | // Distributed under the Thrift Software License |
| 3 | // |
| 4 | // See accompanying file LICENSE or visit the Thrift site at: |
| 5 | // http://developers.facebook.com/thrift/ |
| 6 | |
| 7 | #ifndef _THRIFT_CONCURRENCY_FUNCTION_RUNNER_H |
| 8 | #define _THRIFT_CONCURRENCY_FUNCTION_RUNNER_H 1 |
| 9 | |
| 10 | #include <tr1/functional> |
| 11 | #include "thrift/lib/cpp/concurrency/Thread.h" |
| 12 | |
| 13 | namespace facebook { namespace thrift { namespace concurrency { |
| 14 | |
| 15 | /** |
| 16 | * Convenient implementation of Runnable that will execute arbitrary callbacks. |
| 17 | * Interfaces are provided to accept both a generic 'void(void)' callback, and |
| 18 | * a 'void* (void*)' pthread_create-style callback. |
| 19 | * |
| 20 | * Example use: |
| 21 | * void* my_thread_main(void* arg); |
| 22 | * shared_ptr<ThreadFactory> factory = ...; |
| 23 | * shared_ptr<Thread> thread = |
| 24 | * factory->newThread(shared_ptr<FunctionRunner>( |
| 25 | * new FunctionRunner(my_thread_main, some_argument))); |
| 26 | * thread->start(); |
| 27 | * |
| 28 | * |
| 29 | * @author mrabkin |
| 30 | */ |
| 31 | |
| 32 | class FunctionRunner : public Runnable { |
| 33 | public: |
| 34 | // This is the type of callback 'pthread_create()' expects. |
| 35 | typedef void* (*PthreadFuncPtr)(void *arg); |
| 36 | // This a fully-generic void(void) callback for custom bindings. |
| 37 | typedef std::tr1::function<void()> VoidFunc; |
| 38 | |
| 39 | /** |
| 40 | * Given a 'pthread_create' style callback, this FunctionRunner will |
| 41 | * execute the given callback. Note that the 'void*' return value is ignored. |
| 42 | */ |
| 43 | FunctionRunner(PthreadFuncPtr func, void* arg) |
| 44 | : func_(std::tr1::bind(func, arg)) |
| 45 | { } |
| 46 | |
| 47 | /** |
| 48 | * Given a generic callback, this FunctionRunner will execute it. |
| 49 | */ |
| 50 | FunctionRunner(const VoidFunc& cob) |
| 51 | : func_(cob) |
| 52 | { } |
| 53 | |
| 54 | |
| 55 | void run() { |
| 56 | func_(); |
| 57 | } |
| 58 | |
| 59 | private: |
| 60 | VoidFunc func_; |
| 61 | }; |
| 62 | |
| 63 | }}} // facebook::thrift::concurrency |
| 64 | |
| 65 | #endif // #ifndef _THRIFT_CONCURRENCY_FUNCTION_RUNNER_H |