• Linux C多线程实现生产者消费者


    今天学习了用Linux C进行线程的同步,实现类似生产者消费者的问题。下面我就来分享我的代码

    #include<stdio.h>
    #include<pthread.h>
    #include<stdlib.h>
    #include<unistd.h>
    
    
    pthread_t tid1;
    pthread_t tid2;
    pthread_cond_t cond_id;
    pthread_mutex_t  mutex_id;
    int number = 0;
    int i = 0;
    
    void * thread_printA()
    {
    	while(i<100)
    	{
    		pthread_mutex_lock(&mutex_id);
    		if(number<0)
    		{
    			pthread_cond_wait(&cond_id,&mutex_id);
    		}
    		number--;
    		printf("A");
    		i++;
    	
    		pthread_cond_signal(&cond_id);
    		pthread_mutex_unlock(&mutex_id);
    	}
    }
    
    void * thread_printB()
    {
    	while(i<100)
    	{
    		pthread_mutex_lock(&mutex_id);
    		if(number>=0)
    		{
    			pthread_cond_wait(&cond_id,&mutex_id);
    		}
    		number++;
    		printf("B");
    		i++;
    		pthread_cond_signal(&cond_id);
    		pthread_mutex_unlock(&mutex_id);
    	}
    }
    
    void main()
    {
    	pthread_create(&tid1,NULL,thread_printA,NULL);
    	pthread_create(&tid2,NULL,thread_printB,NULL);
    	pthread_join(tid1,NULL);
    	pthread_join(tid2,NULL);
    }
    

     

  • 相关阅读:
    Intelligence System
    Hawk-and-Chicken
    The Stable Marriage Problem
    HDU 1173 采矿
    HDU 1018 Big Number 斯特林公式
    HDU 1005 Number Sequence
    ZOJ-3941 Kpop Music Party
    Codeforces 939 D Love Rescue
    Codefroces 939 C Convenient For Everybody
    Codeforces 935 C Fifa and Fafa
  • 原文地址:https://www.cnblogs.com/zzlback/p/8949497.html
Copyright © 2020-2023  润新知