Skip to content

Refactor thread local storage#894

Open
Apprentice-Alchemist wants to merge 1 commit intoHaxeFoundation:masterfrom
Apprentice-Alchemist:refactor-tls
Open

Refactor thread local storage#894
Apprentice-Alchemist wants to merge 1 commit intoHaxeFoundation:masterfrom
Apprentice-Alchemist:refactor-tls

Conversation

@Apprentice-Alchemist
Copy link
Contributor

This implementation supports a maximum of 4,294,967,295 tls slots across the lifetime of the process (before the counter overflows). That should be enough, right?

Closes #891

@ncannasse
Copy link
Member

Interesting but I don't think i want to add a map access for every TLS, as we want them to be extra fast, so as much native as possible. We should return null in hl_tls_alloc when we can't alloc and throw an exception on the Haxe side. It's then up to the user to limit his TLS usage and eventually use a Map instead of allocating too many.

@Simn
Copy link
Member

Simn commented Feb 26, 2026

Could we at least run the GC when we can't allocate? I think my original problem was a variant of this:

function main() {
	final tooMany = 513;
	for (_ in 0...tooMany) {
		new sys.thread.Tls();
	}
}

So all these TLS could be freed, but if the GC never runs they aren't.

@ncannasse
Copy link
Member

I guess we could try once before returning null indeed.

@Apprentice-Alchemist
Copy link
Contributor Author

Interesting but I don't think i want to add a map access for every TLS, as we want them to be extra fast, so as much native as possible. We should return null in hl_tls_alloc when we can't alloc and throw an exception on the Haxe side. It's then up to the user to limit his TLS usage and eventually use a Map instead of allocating too many.

HL is the only target (apart from Neko) that uses pthread slots directly, so I don't think this argument makes much sense.
In this case I think consistency between targets is more important than performance.

This approach also solves the GC leak issue mentioned in HaxeFoundation/haxe#12388

@Apprentice-Alchemist
Copy link
Contributor Author

Switched to a new implementation that should be nearly as fast as native implementations.

HL_API hl_tls *hl_tls_alloc( bool gc_value );
HL_API void hl_tls_set( hl_tls *l, void *value );
HL_API void *hl_tls_get( hl_tls *l );
HL_API void hl_tls_free( hl_tls *l );
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an abi breakage, maybe it's better to deprecate it and keep a dummy implementation

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

Successfully merging this pull request may close these issues.

TLS exhaustion

4 participants