Skip to content

Instantly share code, notes, and snippets.

@qwertyowmx
Created January 18, 2023 14:50
Show Gist options
  • Save qwertyowmx/63f5596fab939b0df23fbd9a313a141f to your computer and use it in GitHub Desktop.
Save qwertyowmx/63f5596fab939b0df23fbd9a313a141f to your computer and use it in GitHub Desktop.
C++ Call once sample 1
#include <iostream>
#include <string>
#include <thread>
#include <vector>
#include <mutex> // call once
#include <chrono>
namespace game {
using namespace std::literals::chrono_literals;
struct GameResource {
std::string name;
};
std::once_flag isGameResourcesInitialized{};
std::vector<GameResource> gameResources;
void initializeResources() {
bool canThrowException = true;
std::call_once(isGameResourcesInitialized, [](bool canThrowException) {
gameResources.push_back({ "resource_one" });
gameResources.push_back({ "resource_two" });
std::cout << "Game resources initialized" << std::endl;
}, canThrowException);
}
std::thread startGameThread() {
initializeResources();
return std::thread([]() {
std::thread::id id = std::this_thread::get_id();
std::cout << "Starting game thread with id: " << id << std::endl;
std::cout << "Resources: " << std::endl;
for (GameResource& r : gameResources) {
std::cout << r.name << " from thread " << id << std::endl;
}
std::this_thread::sleep_for(3s);
});
}
void updateGameState() {
std::cout << "Updating some game state..." << std::endl;
}
}
int main()
{
std::thread threadOne = game::startGameThread();
std::thread threadTwo = game::startGameThread();
std::thread threadThree = game::startGameThread();
threadOne.join();
threadTwo.join();
threadThree.join();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment