线程间的互斥

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <pthread.h>
#include <sched.h>
/*
 * 
 */
void *product_f(void *arg);
void *consumer_f(void *arg);
int buffer_has_item = 0;
pthread_mutex_t mutex;
int running = 1;

int main(void){
    pthread_t consumer_t;
    pthread_t product_t;
    
    pthread_mutex_init(&mutex,NULL);
    
    pthread_create(&product_t,NULL,(void*)product_f,NULL);
    pthread_create(&consumer_t,NULL,(void*)consumer_f,NULL);
    
    usleep(1);
    running = 0;
    pthread_join(product_t,NULL);
    pthread_join(consumer_t,NULL);
    
    pthread_mutex_destroy(&mutex);
    
    return 0;  
}

void *product_f(void *arg)
{
    while(running){
        pthread_mutex_lock(&mutex);
        buffer_has_item++;
        printf("product total number:%d\n",buffer_has_item);
        pthread_mutex_unlock(&mutex);
    }
}

void *consumer_f(void *arg)
{
    while(running){
        pthread_mutex_lock(&mutex);
        buffer_has_item--;
        printf("consumbe total number:%d\n",buffer_has_item);
        pthread_mutex_unlock(&mutex);
    }
}


运行结果

product total number:1
product total number:2
product total number:3
product total number:4
product ..............
product total number:70
product total number:71
product total number:72
product total number:73
consumbe total number:72

猜你喜欢

转载自ssh-2009-126-com.iteye.com/blog/1716367