How to sleep or pause a PThread in c on Linux

后端 未结 2 957
长情又很酷
长情又很酷 2020-12-02 16:05

I am developing an application in which I do multithreading. One of my worker threads displays images on the widget. Another thread plays sound. I want to stop/suspend/pause

相关标签:
2条回答
  • 2020-12-02 16:39

    You have your threads poll for "messages" from the UI at regular interval. In other words, UI in one thread posts action messages to the worker threads e.g. audio/video.

    0 讨论(0)
  • 2020-12-02 16:53

    You can use a mutex, condition variable, and a shared flag variable to do this. Let's assume these are defined globally:

    pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
    pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
    int play = 0;
    

    You could structure your playback code like this:

    for(;;) { /* Playback loop */
        pthread_mutex_lock(&lock);
        while(!play) { /* We're paused */
            pthread_cond_wait(&cond, &lock); /* Wait for play signal */
        }
        pthread_mutex_unlock(&lock);
        /* Continue playback */
    }
    

    Then, to play you can do this:

    pthread_mutex_lock(&lock);
    play = 1;
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&lock);
    

    And to pause:

    pthread_mutex_lock(&lock);
    play = 0;
    pthread_mutex_unlock(&lock);
    
    0 讨论(0)
提交回复
热议问题