Created
January 18, 2023 14:50
-
-
Save qwertyowmx/eae2c93f74dd209ced2d1757c6c4087c to your computer and use it in GitHub Desktop.
C++ Call once sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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() { | |
std::call_once(isGameResourcesInitialized, []() { | |
gameResources.push_back({ "resource_one" }); | |
gameResources.push_back({ "resource_two" }); | |
std::cout << "Game resources initialized" << std::endl; | |
}); | |
} | |
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