使用mutex控制while循环的时序

Use mutex to control timing of while loop

我想了解如何使用线程来控制循环内指令的执行。为此,我不能在主函数中使用睡眠,因为那样会阻塞主线程一段时间。相反,我只是想确保如果某个时间还没有过去,则不会到达 while 循环的下一次迭代。目前,我有另一个线程只启用一个名为 go_on 的标志。

它可以工作,但是,有没有办法用互斥来做到这一点?

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

void *thread_proc(void *arg)
{
    int *go_on = (int *)arg;
    while(1)
    {
        sleep(1);
        *(go_on) = 1;
    }
}

int main()
{
    int go_on = 0;

    pthread_t tid;
    pthread_create(&tid, NULL, &thread_proc, (void *)&go_on);

    int counter = 0;    
    while(1)
    {
        while(go_on == 0){};
        go_on = 0;
        counter += 1;
        printf("%d\n", counter);
    }

    return 0;
}

您可以使用信号在线程之间进行通信。

您用一个条件和一个被调用线程锁定的互斥锁阻塞了第一个线程。然后第二个线程发送一个信号来解锁被条件阻塞的线程。

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>

pthread_cond_t cv;
pthread_mutex_t lock;

void *thread2(void *arg)
{
    //Send signal
    pthread_cond_signal(&cv);
}

int main()
{
    //Create thread2
    pthread_t threadId;
    pthread_create(&threadId, NULL, &thread2, NULL);

    //Lock the mutex
    pthread_mutex_lock(&lock);

    //Block the thread on a condition with the locked mutex
    pthread_cond_wait(&cv, &lock);

    printf("The thread is now unblocked");

    //Unlock the mutex
    pthread_mutex_unlock(&lock);

    return 0;
}

根据 MasterRem 的回答,如果您想为某个动作计时,可以执行以下操作,并使用 while 循环重复执行此操作。

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <signal.h>

pthread_cond_t cv = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock;

void *thread2(void *arg)
{
    while(1) {
        sleep(1);
        //Send signal
        pthread_cond_signal(&cv);
    }
}

int main()
{
    //Create thread2
    pthread_t threadId;
    pthread_create(&threadId, NULL, &thread2, NULL);

    //Lock the mutex
    pthread_mutex_init(&lock, NULL);
    pthread_mutex_lock(&lock);

    int counter = 0;

    while(1) {
        //Block the thread on a condition with the locked mutex
        pthread_cond_wait(&cv, &lock);
        counter += 1;
        printf("%d\n", counter);
    }

    //Unlock the mutex
    pthread_mutex_unlock(&lock);

    return 0;
}