Skip to content

Commit 6e1e545

Browse files
sebresterrelln
authored andcommitted
avoid potential RC on ctx->threadLimit, code review;
closes gh-4547; replaces gh-4558
1 parent 0532fe3 commit 6e1e545

File tree

1 file changed

+16
-19
lines changed

1 file changed

+16
-19
lines changed

lib/common/pool.c

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -142,19 +142,17 @@ POOL_ctx* POOL_create_advanced(size_t numThreads, size_t queueSize,
142142
/* Allocate space for the thread handles */
143143
ctx->threads = (ZSTD_pthread_t*)ZSTD_customCalloc(numThreads * sizeof(ZSTD_pthread_t), customMem);
144144
ctx->threadCapacity = 0;
145+
ctx->threadLimit = numThreads;
145146
ctx->customMem = customMem;
146147
/* Check for errors */
147148
if (!ctx->threads || !ctx->queue) { POOL_free(ctx); return NULL; }
148149
/* Initialize the threads */
149-
{ size_t i;
150-
for (i = 0; i < numThreads; ++i) {
151-
if (ZSTD_pthread_create(&ctx->threads[i], NULL, &POOL_thread, ctx)) {
152-
ctx->threadCapacity = i;
153-
POOL_free(ctx);
154-
return NULL;
155-
} }
156-
ctx->threadCapacity = numThreads;
157-
ctx->threadLimit = numThreads;
150+
while (ctx->threadCapacity < numThreads) {
151+
if (ZSTD_pthread_create(&ctx->threads[ctx->threadCapacity++], NULL, &POOL_thread, ctx)) {
152+
--ctx->threadCapacity;
153+
POOL_free(ctx);
154+
return NULL;
155+
}
158156
}
159157
return ctx;
160158
}
@@ -220,23 +218,22 @@ static int POOL_resize_internal(POOL_ctx* ctx, size_t numThreads)
220218
return 0;
221219
}
222220
/* numThreads > threadCapacity */
221+
ctx->threadLimit = numThreads;
223222
{ ZSTD_pthread_t* const threadPool = (ZSTD_pthread_t*)ZSTD_customCalloc(numThreads * sizeof(ZSTD_pthread_t), ctx->customMem);
224223
if (!threadPool) return 1;
225-
/* replace existing thread pool */
224+
/* extend existing thread pool */
226225
ZSTD_memcpy(threadPool, ctx->threads, ctx->threadCapacity * sizeof(ZSTD_pthread_t));
227226
ZSTD_customFree(ctx->threads, ctx->customMem);
228227
ctx->threads = threadPool;
229228
/* Initialize additional threads */
230-
{ size_t threadId;
231-
for (threadId = ctx->threadCapacity; threadId < numThreads; ++threadId) {
232-
if (ZSTD_pthread_create(&threadPool[threadId], NULL, &POOL_thread, ctx)) {
233-
ctx->threadCapacity = threadId;
234-
return 1;
235-
} }
236-
} }
229+
while (ctx->threadCapacity < numThreads) {
230+
if (ZSTD_pthread_create(&threadPool[ctx->threadCapacity++], NULL, &POOL_thread, ctx)) {
231+
--ctx->threadCapacity;
232+
return 1;
233+
}
234+
}
235+
}
237236
/* successfully expanded */
238-
ctx->threadCapacity = numThreads;
239-
ctx->threadLimit = numThreads;
240237
return 0;
241238
}
242239

0 commit comments

Comments
 (0)