AsyncTaskPoolが便利

バックで非同期実行する際などに利用。

AssetsManager とか Download 関係のソースに実装されてるので見様見真似で使ってみる。

Luaからも利用できるように luabinding もさせておくとなおよし。

# 自前のSQLを実行する関数に適用

void Wx::execSqlAsync(const std::string& sql, ResCallback callback)
{
	struct AsyncData
	{
		bool res;
		std::string sql;
	};

	AsyncData* asyncData = new AsyncData;
	asyncData->sql = sql;

	std::function<void(void*)> mainThread = [this, callback, sql](void* param) {
		auto asyncDataInner = reinterpret_cast<AsyncData*>(param);
		callback(asyncDataInner->res, sql);

		delete asyncDataInner;
	};

	AsyncTaskPool::getInstance()->enqueue(AsyncTaskPool::TaskType::TASK_OTHER, mainThread, (void*)asyncData, [this, asyncData] {
		asyncData->res = execSql(asyncData->sql);
	});
}

static int lua_cocos2dx_Wx_execSqlAsync(lua_State* L)
{
	if (nullptr == L)
		return 0;

	int argc = 0;
	Wx* self = nullptr;
	bool ok = true;

#if COCOS2D_DEBUG >= 1
	tolua_Error tolua_err;
	if (!tolua_isusertype(L, 1, "Wx", 0, &tolua_err)) goto tolua_lerror;
#endif

	self = static_cast<Wx*>(tolua_tousertype(L, 1, 0));

#if COCOS2D_DEBUG >= 1
	if (nullptr == self) {
		tolua_error(L, "invalid 'self' in function 'lua_cocos2dx_Wx_execSqlAsync'\n", NULL);
		return 0;
	}
#endif
	argc = lua_gettop(L) - 1;
	if (2 == argc)
	{

		std::string arg0;
		ok &= luaval_to_std_string(L, 2, &arg0, "Wx:execSqlAsync");
		if (!ok)
		{
			tolua_error(L, "invalid arguments in function 'lua_cocos2dx_custom_Wx_execSqlAsync'", nullptr);
			return 0;
		}


#if COCOS2D_DEBUG >= 1
		if (!toluafix_isfunction(L, 3, "LUA_FUNCTION", 0, &tolua_err)) { goto tolua_lerror; }
#endif

		LUA_FUNCTION handler = (toluafix_ref_function(L, 3, 0));

		std::function<void(bool b, const std::string sql)> callback = [L, handler](bool b, const std::string sql) {
			LuaStack* stack = LuaEngine::getInstance()->getLuaStack();
			stack->pushBoolean(b);
			stack->pushString(sql.c_str());
			stack->executeFunctionByHandler(handler, 2);
		};

		self->execSqlAsync(arg0, callback);

		return 0;

	}

	luaL_error(L, "'execSqlAsync' function of Wx has wrong number of arguments: %d, was expecting %d\n", argc, 2);

	return 0;

#if COCOS2D_DEBUG >= 1
	tolua_lerror:
				tolua_error(L, "#ferror in function 'execSqlAsync'.", &tolua_err);
				return 0;
#endif
}