第一题:使用互斥锁或者信号量,实现一个简单的生产者消费者模型 一个线程每秒生产3个苹果,另一个线程每秒消费8个苹果
#include <myhead.h>
pthread_mutex_t m1,m2;
int apple = 0;
void* usrapp(void* data)
{
while(1)
{
pthread_mutex_lock(&m1);
pthread_mutex_lock(&m2);
apple-=8;
printf("还有%d个苹果\n", apple);
pthread_mutex_unlock(&m1);
sleep(1);
}
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&m1,0);
pthread_mutex_init(&m2,0);
pthread_mutex_lock(&m2);
pthread_t id;
pthread_create(&id,0,usrapp,0);
pthread_detach(id);
while(1)
{
pthread_mutex_lock(&m1);
apple+=3;
pthread_mutex_unlock(&m1);
if(apple >=8) {pthread_mutex_unlock(&m2);}
sleep(1);
}
pthread_mutex_destroy(&m1);
pthread_mutex_destroy(&m2);
return 0;
}
第二题:
有一个盘子,盘子里面最多放3个苹果,5个橘子
2个生产者线程,一个每秒放1个苹果,另一个每秒2个橘子
放了苹果就不能放橘子,放了橘子就不能放苹果
2个消费者线程,1号消费者线程每秒消费2个苹果,2号消费者线程,每秒消费3个橘子
#include <myhead.h>
#include <time.h>
#include <stdlib.h>
int orange = 0, apple = 0;
pthread_mutex_t ap_m;
pthread_mutex_t or_m;
pthread_mutex_t m;
pthread_cond_t cond1;
pthread_cond_t cond2;
void *apple_run(void *arg){
while(1){
pthread_mutex_lock(&ap_m);
pthread_cond_wait(&cond1, &ap_m);
apple -= 2;
printf("消费苹果2个\n");
pthread_mutex_unlock(&ap_m);
sleep(1);
}
}
void *orange_run(void *arg){
while(1){
pthread_mutex_lock(&or_m);
pthread_cond_wait(&cond2, &or_m);
orange -= 3;
printf("消费橘子3个\n");
pthread_mutex_unlock(&or_m);
sleep(1);
}
}
void *produce(void *arg){
while(1){
pthread_mutex_lock(&m);
if(orange < 4){
pthread_mutex_lock(&or_m);
orange += 2;
printf("orange:%d\n", orange);
pthread_mutex_unlock(&or_m);
}else{
pthread_mutex_unlock(&m);
continue;
}
if(apple >= 2){
pthread_cond_signal(&cond1);
}
if(orange >= 3){
pthread_cond_signal(&cond2);
}
sleep(1);
pthread_mutex_unlock(&m);
}
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&ap_m, 0);
pthread_mutex_init(&or_m, 0);
pthread_mutex_init(&m, 0);
pthread_cond_init(&cond1, 0);
pthread_cond_init(&cond2, 0);
pthread_t ap;
pthread_t or;
pthread_t pro;
pthread_create(&pro, 0, produce, 0);
pthread_create(&ap, 0, apple_run, 0);
pthread_create(&or, 0, orange_run, 0);
pthread_detach(ap);
pthread_detach(or);
pthread_detach(pro);
while(1){
pthread_mutex_lock(&m);
if(apple < 3){
apple += 1;
printf("apple:%d\n", apple);
pthread_mutex_unlock(&ap_m);
}else{
pthread_mutex_unlock(&m);
continue;
}
if(apple >= 2){
pthread_cond_signal(&cond1);
}
if(orange >= 3){
pthread_cond_signal(&cond2);
}
sleep(1);
pthread_mutex_unlock(&m);
}
return 0;
}
第三题
#include <myhead.h>
int getch();
int main(int argc, const char *argv[])
{
int a;
a = getch();
printf("%d", a);
return 0;
}
实现现象:将终端输入的字符转换为其对应的ASCII码值返回