C-Thread-Pool icon indicating copy to clipboard operation
C-Thread-Pool copied to clipboard

Is it possible to wait for a specific task?

Open giovancris opened this issue 1 year ago • 1 comments

Hello!

I have a simple question: We have the function void thpool_wait(threadpool); that wait for all queued jobs to finish, I was wondering if there was the possibility to wait for a specific job, something like thpool_wait(threadpool, jobID);

Thank you in advance

giovancris avatar Apr 18 '24 05:04 giovancris

Per‑job state multiplies complexity. The simplest, most flexible pattern is to push the signaling logic into your job function itself, using a lightweight synchronization primitive that’s scoped just to that job: 1.Before you enqueue the job, create a small struct holding: int job_id;, a pthread_mutex_t + pthread_cond_t 2.Wrap your actual work

void job_wrapper(void *arg) {
    job_handle_t *h = arg;
    perform_real_work(h->job_id);
    pthread_mutex_lock(&h->m);
    h->done = 1;
    pthread_cond_signal(&h->c);
    pthread_mutex_unlock(&h->m);
}

3.Enqueue the wrapper

job_handle_t h = { .job_id = next_id(), .done = 0 };
pthread_mutex_init(&h.m, NULL);
pthread_cond_init(&h.c, NULL);
thpool_add_work(pool, job_wrapper, &h);

4.Wait for just that job

pthread_mutex_lock(&h.m);
while (!h.done) {
    pthread_cond_wait(&h.c, &h.m);
}
pthread_mutex_unlock(&h.m);

npc1054657282 avatar Apr 20 '25 13:04 npc1054657282