c语言实现消费者生产者模型以及两个线程交叉打印

突然想写个博客吧。
内容就是实现消费者生产者模型,以及实现两个线程交叉打印吧

这个模型是黑马程序员视频上copy来的,自己来练练

两者都是用的互斥锁+条件变量(信号量不喜欢用,就不练了,感觉那两个够用了,嘿嘿嘿)

代码都很简单,我就不打备注啦吧,如果需要注释,你们留言?我添加?哈哈哈哈哈哈哈哈

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

struct Msg{
    int num;
    struct Msg *next;
};


struct Msg *head;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t has_data = PTHREAD_COND_INITIALIZER;

void *consumer(void *arg){
	while(1){
		struct Msg *temp;

		pthread_mutex_lock(&mutex);

		if(head==NULL){
			pthread_cond_wait(&has_data,&mutex);
		}

		temp = head;
		head = head->next;

		pthread_mutex_unlock(&mutex);

		doIwant();

		free(temp);

		sleep(rand()%3);
	}
	return NULL;
}

void *processor(void *arg){
	while(1){
		struct Msg *m = malloc(sizeof(struct Msg));
		m->num = rand()%1000+1;

		pthread_mutex_lock(&mutex);

		m->next = head;
		head = m;

		pthread_mutex_unlock(&mutex);

		pthread_cond_signal(&has_data);

		sleep(rand()%3);
	}
	return NULL;
}


int main(){

	srand(time(NULL));

	pthread_t pid,cid;
	pthread_create(&pid,NULL,processor,NULL);
	pthread_create(&cid,NULL,consumer,NULL);

	pthread_join(pid,NULL);
	pthread_join(pid,NULL);
}

下面是两个线程交叉打印,为了偷懒,线程结束就直接exit(0)了,哈哈,不错就行,哦啦啦啦啦

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

int arr1[3]={1,2,3};
char arr2[3]={'A','B','C'};

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t con1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t con2 = PTHREAD_COND_INITIALIZER;

void *printfnum(void* arg){
    for(int i = 0;i<3;i++){
        pthread_mutex_lock(&mutex);
        
        sleep(1);
        printf("%d\n",arr1[i]);
        if(i==2){
            i=-1;
        }
        
        pthread_cond_signal(&con2);
        
        pthread_cond_wait(&con1,&mutex);
        pthread_mutex_unlock(&mutex);
        
    }
    exit(0);
    return NULL;
}
void *printfchar(void* arg){
    for(int i = 0;i<3;i++){
        sleep(1);
        
        pthread_mutex_lock(&mutex);
        
        printf("%c\n",arr2[i]);
   

 if(i==2){
        i=-1;
    }
        
        pthread_cond_signal(&con1);
        
        pthread_cond_wait(&con2,&mutex);
        pthread_mutex_unlock(&mutex);
        
    }
    exit(0);
    return NULL;
}

int main(){
    pthread_t p1,p2;
    
    pthread_create(&p1, NULL, printfnum, NULL);
    pthread_create(&p2, NULL, printfchar, NULL);
    
    pthread_join(p1,NULL);
    pthread_join(p2,NULL);
    
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&con1);
    pthread_cond_destroy(&con2);
    
    return 0;
}

两个线程函数中的if(i==2){ i=-1; }这里是为了一个一直循环打印下去,然后数组下标也不会越界,我感觉这么处理还挺好?
在printfchar函数中,先sleep一下,是因我想让打印数字先拿到锁。

大家加油!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值