Alternative pthread_timedjoin_np

I'm trying to figure out how to get rid of the pthread_timedjoin_np dependency, because I'm trying to create some code in OSX.

Right now I have a queue of threads that I exit from doing this pthread_timedjoin_np, and if they do not return, they will be thrown into the queue.

The end of the thread_function called for each thread has pthread_exit (0); so that the receiving stream can check for a zero return value.

I thought that I could try using pthread_cond_timedwait () to achieve a similar effect, however, I think I have no step.

I thought I could make worker thread A a condition signal AND pthread_exit () in the mutex, and worker thread B could wake up after the signal, and then pthread_join (). The problem is that Thread B does not know which thread has dropped the conditional signal. Should I explicitly pass this as part of the conditional signal, or what?

thank

Derek

+5
source share
3 answers

the line of producer-consumer. Have the thread queue * yourself, and therefore their results (if any) are queued before they exit. Wait in line.

No polling, no delay.

With your current design you will need to join (), the returned threads will receive valueptr and guarantee that they will be destroyed.

, - , , ( // )?

+1

pthread_timedjoin_np. , :

struct args {
    int joined;
    pthread_t td;
    pthread_mutex_t mtx;
    pthread_cond_t cond;
    void **res;
};

static void *waiter(void *ap)
{
    struct args *args = ap;
    pthread_join(args->td, args->res);
    pthread_mutex_lock(&args->mtx);
    args->joined = 1;
    pthread_mutex_unlock(&args->mtx);
    pthread_cond_signal(&args->cond);
    return 0;
}

int pthread_timedjoin_np(pthread_t td, void **res, struct timespec *ts)
{
    pthread_t tmp;
    int ret;
    struct args args = { .td = td, .res = res };

    pthread_mutex_init(&args.mtx, 0);
    pthread_cond_init(&args.cond, 0);
    pthread_mutex_lock(&args.mtx);

    ret = pthread_create(&tmp, 0, waiter, &args);
    if (ret) goto done;

    do ret = pthread_cond_timedwait(&args.cond, &args.mtx, ts);
    while (!args.joined && ret != ETIMEDOUT);

    pthread_mutex_unlock(&args.mtx);

    pthread_cancel(tmp);
    pthread_join(tmp, 0);

    pthread_cond_destroy(&args.cond);
    pthread_mutex_destroy(&args.mtx);

    return args.joined ? 0 : ret;
}

, , .

+4

alarm.

pthread , ( pthread_timedjoin_np).

pthread_timedjoin_np ETIMEOUT .

  • set alarm, alarm "TIMEOUT".
  • , pthread_cancel . ( - ).
  • pthread_join .
  • reset alarm

: github

0

All Articles