转:学习多线程之互斥锁、条件变量-linux多线程初学者

来源:互联网 发布:数据粒度举例 编辑:程序博客网 时间:2024/04/29 20:41

今天费了好久得劲才把这个程序调好,虽然对于略懂linux的人来说这不算什么,但是自己还是很开心!下面的程序验证通过了。实现的是子线程循环 10 次,接着主线程循环 100 次,接着又回到子线程循环 10 次,接着再回到主线程又循环 100 次,如此循环50次。

#include <pthread.h>   #include <stdio.h>    // 互斥锁,条件变量   pthread_mutex_t mutex;  pthread_cond_t cond;  void main_thread_func();void *subthread_func(); int main_thread=0;int sub_thread=0; // 循环次数   static int main_count = 0;  static int subthread_count = 0;  int main(int argc, char **argv)  {      pthread_t tid;      pthread_mutex_init(&mutex, NULL);      pthread_cond_init(&cond, NULL);        pthread_create(&tid, NULL, subthread_func, NULL);      main_thread_func();      pthread_join(tid, NULL);        return 0;  }void *subthread_func()  {       while(1)       {  int i=0;   for(  i = 0; i <10; i++)  //因为实现的是子线程先运行          {               printf("subthread: %d\n", i+1);            } while(1) {     pthread_mutex_lock(&mutex);     if(main_thread==1)             {              pthread_cond_signal(&cond);                  pthread_mutex_unlock(&mutex);                  break;               }             pthread_mutex_unlock(&mutex);         }         pthread_mutex_lock(&mutex); sub_thread=1; pthread_cond_wait(&cond, &mutex);  sub_thread=0; pthread_mutex_unlock(&mutex);  ++subthread_count;           if (subthread_count >= 50)           {              printf("subthread loop 50 times\n");              break;           }       }   return (void *)0;    }void main_thread_func()  {      while(1) //该循环是为了实现50次     {  int i=0;pthread_mutex_lock(&mutex);        main_thread=1;pthread_cond_wait(&cond, &mutex); main_thread=0;pthread_mutex_unlock(&mutex);for ( i = 0; i <100; i++)          {             printf("main thread: %d\n", i+1);          }         while(1) //该循环是为了实现主线程和子线程的多次交替        {   pthread_mutex_lock(&mutex);   if(sub_thread==1)           {            pthread_cond_signal(&cond);  //唤醒 每次唤醒都必须在互斥锁下,互斥锁都是成对出现,要记得解锁哦!              pthread_mutex_unlock(&mutex);                break;             }          pthread_mutex_unlock(&mutex);        }           ++main_count;          if (main_count >= 50)          {             printf("main thread loop 50 times\n");             break;          }     }                 }  





0 0
原创粉丝点击