samtools / htslib

C library for high-throughput sequencing data formats
Other
783 stars 447 forks source link

Avoid possible race when selecting nibble2base implementation #1786

Closed daviesrob closed 1 month ago

daviesrob commented 1 month ago

Selecting which version of nibble2base() to use on first call is fine in a single thread, but may lead to a race in multi-threaded code. While this is likely harmless (the value stored to the function pointer will always be the same, and the update will probably be a single store), it is best to avoid the problem by making the selection at library initialisation, before any threads have started.

As the optimised nibble2base_ssse3() already uses gcc function attributes, it seems reasonable to use attribute((constructor)) on the function that selects the version to use. If the constructor does not run, it will use the non-optimised version, which is a safe default.

rhpvorderman commented 1 day ago

Thanks for looking into this. Doing the dynamic update at load makes more sense than doing it at function call. I will use this in my code as well from now on.