【问题标题】:Use mutex to control timing of while loop使用互斥锁控制while循环的时间
【发布时间】:2018-07-11 15:54:43
【问题描述】:

我想了解如何使用线程来控制循环内指令的执行。为此,我不能在主函数中使用睡眠,因为这会阻塞主线程一段时间。相反,我只想确保如果还没有经过某个时间,则不会到达 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;
}

【问题讨论】:

  • 那么你知道什么是互斥锁以及如何使用它吗?
  • 如果你不想让你的主线程休眠,你不能只使用 gettimeofday 吗?
  • 另一种方法可能是另一个线程(包含main中的代码),通过信号量与thread_proc同步
  • @EugeneSh。概念我懂,但是不知道怎么用
  • 最简单的事情就是用互斥锁“保护”你现有的标志。无论如何你必须这样做,因为你可能有一些竞争条件。

标签: c while-loop pthreads iteration mutex


【解决方案1】:

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

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

#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;
}

【讨论】:

    【解决方案2】:

    根据 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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-23
      • 1970-01-01
      相关资源
      最近更新 更多