Created
January 18, 2023 14:50
-
-
Save qwertyowmx/63f5596fab939b0df23fbd9a313a141f to your computer and use it in GitHub Desktop.
C++ Call once sample 1
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() { | |
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