Linux多線程編程 – sleep 和 pthread_cond_timedwait

來源:互聯網
上載者:User

#include <stdio.h>
#include <stdlib.h>

int flag = 1;
void * thr_fn(void * arg) {
  while (flag){
    printf("******\n");
    sleep(10);
  }
  printf("sleep test thread exit\n");
}
 
int main() {
  pthread_t thread;
  if (0 != pthread_create(&thread, NULL, thr_fn, NULL)) {
    printf("error when create pthread,%d\n", errno);
    return 1;
  }
 
  char c ;
  while ((c = getchar()) != 'q');
 
  printf("Now terminate the thread!\n");
  flag = 0;
  printf("Wait for thread to exit\n");
  pthread_join(thread, NULL);
  printf("Bye\n");
  return 0;
}

輸入q後,需要等線程從sleep中醒來(由掛起狀態變為運行狀態),即最壞情況要等10s,線程才會被join。採用sleep的缺點:不能及時喚醒線程。

 

採用pthread_cond_timedwait函數,條件到了,線程即會被join,可及時喚醒線程。實現的如下:

#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include <pthread.h>
#include <errno.h>
 
static pthread_t thread;
static pthread_cond_t cond;
static pthread_mutex_t mutex;
static int flag = 1;
 
void * thr_fn(void * arg)
{
  struct timeval now;
  struct timespec outtime;
  pthread_mutex_lock(&mutex);
  while (flag) {
    printf("*****\n");
    gettimeofday(&now, NULL);
    outtime.tv_sec = now.tv_sec + 5;
    outtime.tv_nsec = now.tv_usec * 1000;
    pthread_cond_timedwait(&cond, &mutex, &outtime);
  }
  pthread_mutex_unlock(&mutex);
  printf("cond thread exit\n");
}
 
int main(void)
{
  pthread_mutex_init(&mutex, NULL);
  pthread_cond_init(&cond, NULL);
  if (0 != pthread_create(&thread, NULL, thr_fn, NULL)) {
    printf("error when create pthread,%d\n", errno);
    return 1;
  }
  char c ;
  while ((c = getchar()) != 'q');
  printf("Now terminate the thread!\n");

  pthread_mutex_lock(&mutex);
  flag = 0;
  pthread_cond_signal(&cond);
  pthread_mutex_unlock(&mutex);
  printf("Wait for thread to exit\n");
  pthread_join(thread, NULL);
  printf("Bye\n");
  return 0;
}

pthread_cond_timedwait()函數阻塞住調用該函數的線程,等待由cond指定的條件被觸發(pthread_cond_broadcast() or pthread_cond_signal())。

  當pthread_cond_timedwait()被調用時,調用線程必須已經鎖住了mutex。函數pthread_cond_timedwait()會對mutex進行【解鎖和執行對條件的等待】(原子操作)。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.