线程自己挂自己后 为啥不能被唤醒了?

在线程回调函数内做了一个判断,在某种条件下自己挂起自己,之后再在别的线程唤醒,resumethread()没有生效。

ChatGPT尝试为您解答,仅供参考
在一个线程内部调用 suspendthread() 和 resumethread() 是不合法的,会导致线程阻塞而无法继续执行。

如果你想在线程内部进行挂起和唤醒操作,建议使用其他的线程同步机制,比如互斥锁、信号量或者条件变量。这些机制都可以在线程内部使用,让线程在合适的时候进行挂起和唤醒。

例如,你可以使用互斥锁和条件变量来实现线程的挂起和唤醒:

#include <pthread.h>

pthread_mutex_t mutex; // 互斥锁
pthread_cond_t cond;   // 条件变量

void *thread_func(void *arg)
{
    pthread_mutex_lock(&mutex); // 加锁
    while (some_condition)
    {                                      // 当 some_condition 为真时
        pthread_cond_wait(&cond, &mutex); // 等待条件变量
    }
    pthread_mutex_unlock(&mutex); // 解锁
    // do something
    ...
}

int main()
{
    pthread_t thread;
    pthread_create(&thread, NULL, thread_func, NULL); // 创建新线程

    // 唤醒线程
    pthread_mutex_lock(&mutex);      // 加锁
    some_condition = false;          // 修改 some_condition
    pthread_cond_signal(&cond);      // 发送信号
    pthread_mutex_unlock(&mutex); // 解锁
    pthread_join(thread, NULL);      // 等待线程结束
    return 0;
}

在上面的代码中,我们使用了互斥锁和条件变量来实现线程的挂起和唤醒。当线程执行到 pthread_cond_wait() 时,它会自动释放互斥锁,并挂起自己;当其他线程调用 pthread_cond_signal() 时,被挂起的线程会被唤醒,并重新获取互斥锁。


另外,你也可以使用信号量来实现线程的挂起和唤醒:

#include <semaphore.h>

sem_t sem; // 信号量

void *thread_func(void *arg)
{
    sem_wait(&sem); // 等待信号量
    // do something
    ...
}

int main()
{
    pthread_t thread;
    pthread_create(&thread, NULL, thread_func, NULL); // 创建新线程

    // 唤醒线程
    sem_post(&sem); // 发送信号

    pthread_join(thread, NULL); // 等待线程结束
    return 0;
}

在上面的代码中,我们使用了信号量来实现线程的挂起和唤醒。当线程执行到 sem_wait() 时,如果信号量的值为 0,则线程会挂起;当其他线程调用 sem_post() 时,信号量的值会增加 1,并唤醒被挂起的线程。


总之,如果你想在线程内部进行挂起和唤醒操作,建议使用其他的线程同步机制,比如互斥锁、信号量或者条件变量。这些机制都可以在线程内部使用,让线程在合适的时候进行挂起和唤醒。