Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

It is thread safe? #74

Open
paulocoutinhox opened this issue Jan 22, 2023 · 3 comments
Open

It is thread safe? #74

paulocoutinhox opened this issue Jan 22, 2023 · 3 comments

Comments

@paulocoutinhox
Copy link

Hi,

It is thread-safe?

Thanks.

@paulocoutinhox
Copy link
Author

Hi @mariusbancila,

Can you confirm this?

@ocbj
Copy link

ocbj commented Aug 25, 2023

Anyone? I hope to use this for generating resource ids. But I can't unless it's thread safe.

@ocbj
Copy link

ocbj commented Aug 27, 2023

So it isn't thread safe. The generator you provide is stored as a shared_ptr in uuid generator.

An easy workaround would be to use thread_local.
Here's what I went with:

inline uuids::uuid GenerateUuid(){
	thread_local std::unique_ptr<uuids::uuid_random_generator> uuidGenerator = nullptr;
	
	if(!uuidGenerator) {
		std::random_device rd;
		auto threadIdHash = std::hash<std::thread::id>{}(std::this_thread::get_id());
		uint64_t mixedSeed = static_cast<uint64_t>(rd()) ^ static_cast<uint64_t>(threadIdHash);
		
		thread_local std::mt19937 generator(static_cast<unsigned int>(mixedSeed));
		uuidGenerator = std::make_unique<uuids::uuid_random_generator>(generator);
	}
	
	auto& gen = *uuidGenerator.get();
	return gen();
}

For my use case the overhead of having one instance per thread is worth it, because it's not that much memory & I'm recycling threads in a thread pool. Hope this helps someone.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants