Fix Linux usleep Thread Blocking

If a thread gets stuck due to using the usleep function, it may be because the function blocks the current thread for a specified time. Consider using alternative methods to pause the thread and avoid it getting blocked and causing a deadlock.

An alternative approach is to use the pthread_cond_timedwait function, which allows for waiting for a condition variable to occur within a specified time frame. pthread_mutex can be used in conjunction to ensure synchronicity between thread wait and wake-up.

Here is an example code:

#include <stdio.h>
#include <pthread.h>
#include <time.h>

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* thread_func(void* arg) {
    struct timespec ts;
    clock_gettime(CLOCK_REALTIME, &ts);
    ts.tv_sec += 1;  // 等待1秒钟

    pthread_mutex_lock(&mutex);
    pthread_cond_timedwait(&cond, &mutex, &ts);
    pthread_mutex_unlock(&mutex);

    printf("Thread woke up\n");
    return NULL;
}

int main() {
    pthread_t tid;
    pthread_create(&tid, NULL, thread_func, NULL);
    pthread_join(tid, NULL);

    return 0;
}

In the example above, the thread will be awakened after waiting for 1 second. If no other thread calls the pthread_cond_signal or pthread_cond_broadcast function to wake up the thread within 1 second, the thread will be automatically awakened.

This can prevent the issue of threads getting stuck by avoiding the use of the usleep function.

bannerAds