简体   繁体   中英

Wake up a sleeping thread, else sleep for N seconds

I am writing a C program using POSIX threads.

Let N be a global variable. I have a thread that calls sleep(N). A different thread then changes the value of N. How can I have my original thread that called sleep(N) wake up, and call sleep again on the new value of N?

To rephrase, I want to sleep for N, if N gets updated, wake up, and sleep for the new value of N.

I have looked into pthread_cond_wait and pthread_cond_timedwait, but I do not think it is useful in my case, as I would need the threads to be asleep for a specific amount of time. I need my thread to continuously sleep and wake up every N seconds.

As user1930928 showed below, I think I need to use pthread_cond_timedwait

The question and the objective is stil not clear to me...but let me provide a code skeleton so that you can clarify your question better.

Initialize N.
Initialize mutex.
Initialize CV.

T1()
{
    mutex_lock();
    while (1) {
        copy_of_N = N;       
        pthread_cond_timedwait(N); // drops the mutex
        ....
        ....

        // timed wait done OR wakeup was issued on cond var
        if (copy_of_N != N) {
            // N was changed
            do_something();
        } else {
            // N was not changed
            do_something_else();
        }

        // either way, goto sleep on N.                   
    }
    mutex_unlock();
}

T2()
{
    mutex_lock();
    change N;
    pthread_cond_signal();
    mutex_unlock();
}

Please clarify your question based on whether the above skeleton matches your req or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM