avoid potential RC on ctx->threadLimit, code review;

closes gh-4547; replaces gh-4558
This commit is contained in:
Sergey G. Brester (sebres)
2026-03-02 14:39:17 -05:00
committed by Nick Terrell
parent 0532fe3e8a
commit 6e1e545916
+16 -19
View File
@@ -142,19 +142,17 @@ POOL_ctx* POOL_create_advanced(size_t numThreads, size_t queueSize,
/* Allocate space for the thread handles */ /* Allocate space for the thread handles */
ctx->threads = (ZSTD_pthread_t*)ZSTD_customCalloc(numThreads * sizeof(ZSTD_pthread_t), customMem); ctx->threads = (ZSTD_pthread_t*)ZSTD_customCalloc(numThreads * sizeof(ZSTD_pthread_t), customMem);
ctx->threadCapacity = 0; ctx->threadCapacity = 0;
ctx->threadLimit = numThreads;
ctx->customMem = customMem; ctx->customMem = customMem;
/* Check for errors */ /* Check for errors */
if (!ctx->threads || !ctx->queue) { POOL_free(ctx); return NULL; } if (!ctx->threads || !ctx->queue) { POOL_free(ctx); return NULL; }
/* Initialize the threads */ /* Initialize the threads */
{ size_t i; while (ctx->threadCapacity < numThreads) {
for (i = 0; i < numThreads; ++i) { if (ZSTD_pthread_create(&ctx->threads[ctx->threadCapacity++], NULL, &POOL_thread, ctx)) {
if (ZSTD_pthread_create(&ctx->threads[i], NULL, &POOL_thread, ctx)) { --ctx->threadCapacity;
ctx->threadCapacity = i; POOL_free(ctx);
POOL_free(ctx); return NULL;
return NULL; }
} }
ctx->threadCapacity = numThreads;
ctx->threadLimit = numThreads;
} }
return ctx; return ctx;
} }
@@ -220,23 +218,22 @@ static int POOL_resize_internal(POOL_ctx* ctx, size_t numThreads)
return 0; return 0;
} }
/* numThreads > threadCapacity */ /* numThreads > threadCapacity */
ctx->threadLimit = numThreads;
{ ZSTD_pthread_t* const threadPool = (ZSTD_pthread_t*)ZSTD_customCalloc(numThreads * sizeof(ZSTD_pthread_t), ctx->customMem); { ZSTD_pthread_t* const threadPool = (ZSTD_pthread_t*)ZSTD_customCalloc(numThreads * sizeof(ZSTD_pthread_t), ctx->customMem);
if (!threadPool) return 1; if (!threadPool) return 1;
/* replace existing thread pool */ /* extend existing thread pool */
ZSTD_memcpy(threadPool, ctx->threads, ctx->threadCapacity * sizeof(ZSTD_pthread_t)); ZSTD_memcpy(threadPool, ctx->threads, ctx->threadCapacity * sizeof(ZSTD_pthread_t));
ZSTD_customFree(ctx->threads, ctx->customMem); ZSTD_customFree(ctx->threads, ctx->customMem);
ctx->threads = threadPool; ctx->threads = threadPool;
/* Initialize additional threads */ /* Initialize additional threads */
{ size_t threadId; while (ctx->threadCapacity < numThreads) {
for (threadId = ctx->threadCapacity; threadId < numThreads; ++threadId) { if (ZSTD_pthread_create(&threadPool[ctx->threadCapacity++], NULL, &POOL_thread, ctx)) {
if (ZSTD_pthread_create(&threadPool[threadId], NULL, &POOL_thread, ctx)) { --ctx->threadCapacity;
ctx->threadCapacity = threadId; return 1;
return 1; }
} } }
} } }
/* successfully expanded */ /* successfully expanded */
ctx->threadCapacity = numThreads;
ctx->threadLimit = numThreads;
return 0; return 0;
} }