acl/lib_fiber/cpp/include/fiber/fiber.hpp

181 lines
3.4 KiB
C++
Raw Normal View History

#pragma once
2016-12-08 13:13:30 +08:00
#include <stddef.h>
struct ACL_FIBER;
namespace acl {
/**
*
*/
class fiber
{
public:
fiber(void);
virtual ~fiber(void);
/**
*
* @param stack_size {size_t}
*/
2016-08-19 22:31:05 +08:00
void start(size_t stack_size = 320000);
/**
* 退
* @return {bool} false 退
*/
bool kill(void);
/**
* 退
* @return {bool} 退
*/
bool killed(void) const;
/**
* ID
* @return {int}
*/
int get_id(void) const;
/**
* ID
*/
static int self(void);
/**
* API
* return {int}
*/
int get_errno(void) const;
/**
*
* @param errnum {int}
*/
void set_errno(int errnum);
/**
*
*/
static void schedule(void);
/**
*
*/
2016-09-22 22:50:45 +08:00
static void schedule_stop(void);
public:
/**
* ()
*/
static void yield(void);
/**
*
*/
static void switch_to_next(void);
/**
*
* @param f {fiber&}
*/
static void ready(fiber& f);
/**
* 线线 hook API
* hook API
* @param on {bool}
*/
static void hook_api(bool on);
public:
/**
* C
* @return {ACL_FIBER *}
*/
ACL_FIBER *get_fiber(void) const;
protected:
/**
* start
*
*/
virtual void run(void) = 0;
private:
ACL_FIBER *f_;
static void fiber_callback(ACL_FIBER *f, void *ctx);
};
} // namespace acl
#if defined(__GNUC__) && (__GNUC__ > 6 ||(__GNUC__ == 6 && __GNUC_MINOR__ >= 0))
# ifndef ACL_USE_CPP11
# define ACL_USE_CPP11
# endif
#endif
#ifdef ACL_USE_CPP11
#include <functional>
namespace acl
{
class go_fiber
{
public:
go_fiber(void) {}
go_fiber(size_t stack_size) : stack_size_(stack_size) {}
void operator=(std::function<void()> fn);
private:
size_t stack_size_ = 320000;
};
} // namespace acl
#define go acl::go_fiber()=
#define go_stack(size) acl::go_fiber(size)=
/**
* static void fiber1(void)
* {
* printf("fiber: %d\r\n", acl::fiber::self());
* }
*
* static void fiber2(acl::string& buf)
* {
* printf("in fiber: %d, buf: %s\r\n", acl::fiber::self(), buf.c_str());
* buf = "world";
* }
*
* static void fiber3(const acl::string& buf)
* {
* printf("in fiber: %d, buf: %s\r\n", acl::fiber::self(), buf.c_str());
* }
*
* static test(void)
* {
* go fiber1;
*
* acl::string buf("hello");
*
* go[&] {
* fiber2(buf);
* };
*
* go[=] {
* fiber3(buf);
* };
*
* go[&] {
* fiber3(buf);
* };
* }
*/
#endif