條件量使用可能出現問題(一)

來源:互聯網
上載者:User

      1 #include<stdio.h>
      2 #include<stddef.h>
      3 #include<pthread.h>
      4 #include<unistd.h>
      5 int i=1;
      6 pthread_mutex_t mutex;
      7 pthread_cond_t cond;
      8
      9 void * Task1()
     10 {
     11         for(i=1;i<9;i++)
     12         {
     13                 pthread_mutex_lock(&mutex);
     14                 if(i%3!=0)printf("In the Task1:%d\n",i);
     15                 else pthread_cond_signal(&cond);
     16                 pthread_mutex_unlock(&mutex);
     17                 sleep(1);
     18         }
     19         return NULL;
     20 }
     21
     22 void * Task2()
     23 {
     24         while(i<9)
     25         {
     26                 pthread_mutex_lock(&mutex);
     27                 if(i%3!=0)
     28                 pthread_cond_wait(&cond,&mutex);//////////由於i=8就截止,導致Task2一直處於wait狀態
     29
     30                 printf("In the Task2:\t%d\n",i);
     31                 pthread_mutex_unlock(&mutex);
     32                 sleep(1);
     33         }
     34         return NULL;
     35
     36 }
     37
     38
     39 int main()
     40 {
     41         pthread_t t_id1,t_id2;
     42         int succ;
     43 
     44         pthread_mutex_init(&mutex,NULL);
     45         pthread_cond_init(&cond,NULL);
     46
     47         succ=pthread_create(&t_id1,NULL,Task1,NULL);
     48         if(succ){printf("Failure in create thread!\n");return NULL;}
     49
     50         succ=pthread_create(&t_id2,NULL,Task2,NULL);
     51         if(succ){printf("Failure in create thread2!\n");return NULL;}
     52
     53         pthread_join(t_id1,NULL);
     54         pthread_join(t_id2,NULL);
     55
     56         pthread_mutex_destroy(&mutex);
     57         pthread_cond_destroy(&cond);
     58         return NULL;
     59 }
 

在使用pthread_cond_wait(),時需要考慮處於等待的狀態在最後是否會退出,當上述程式i=8時,出現了一直等待的狀態。

解決方案1:在設定條件時,讓最後一次調用時,wait 那個進程不處於等待中;

解決方案2:使用pthread_cond_timedwait()

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.