第一题:
使用互斥锁或者信号量,实现一个简单的生产者消费者模型 一个线程每秒生产3个苹果,另一个线程每秒消费8个苹果
int apple=0;
pthread_mutex_t m;
void* run1(void* arg){
while(1){
pthread_mutex_lock(&m);
if(apple>=8){
apple-=8;
printf("a消费8个苹果,现在苹果数量为:%d\n",apple);
sleep(1);
}
pthread_mutex_unlock(&m);
}
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&m,0);
pthread_t id1;
pthread_create(&id1,0,run1,0);
pthread_detach(id1);
while(1){
pthread_mutex_lock(&m);
apple +=3;
printf("b生产了3个苹果,现在苹果数量为:%d\n",apple);
pthread_mutex_unlock(&m);
sleep(1);
}
return 0;
}
第二题:
有一个盘子,盘子里面最多放3个苹果,5个橘子 2个生产者线程,一个每秒放1个苹果,另一个每秒2个橘子 放了苹果就不能放橘子,放了橘子就不能放苹果 2个消费者线程,1号消费者线程每秒消费2个苹果,2号消费者线程,每秒消费3个橘子
int apple=0;
int orange=0;
pthread_mutex_t m;
pthread_mutex_t x;
pthread_mutex_t y;
pthread_cond_t a;
pthread_cond_t b;
void* run1(void* arg){
while(1){
pthread_mutex_lock(&x);
pthread_cond_wait(&a,&x);
apple-=2;
printf("a消费2个苹果,现在苹果数量为:%d\n",apple);
pthread_mutex_unlock(&x);
sleep(1);
}
}
void* run2(void* arg){
while(1){
pthread_mutex_lock(&y);
pthread_cond_wait(&b,&y);
orange-=3;
printf("b消费3个橘子,现在橘子数量为:%d\n",orange);
pthread_mutex_unlock(&y);
sleep(1);
}
}
void* run3(void* arg){
while(1){
if(apple<3){
pthread_mutex_lock(&m);
apple +=1;
printf("c生产了1个苹果,现在苹果数量为:%d\n",apple);
pthread_mutex_unlock(&m);
}
if(apple>=2){
pthread_cond_signal(&a);
}
sleep(1);
}
}
void* run4(void* arg){
while(1){
if(orange<=3){
pthread_mutex_lock(&m);
orange +=2;
printf("d生产了2个橘子,现在数量橘子为:%d\n",orange);
pthread_mutex_unlock(&m);
}
if(orange>=3){
pthread_cond_signal(&b);
}
sleep(1);
}
}
int main(int argc, const char *argv[])
{
pthread_mutex_init(&m,0);
pthread_mutex_init(&x,0);
pthread_mutex_init(&y,0);
pthread_cond_init(&a,0);
pthread_cond_init(&b,0);
pthread_t id1,id2,id3,id4;
pthread_create(&id1,0,run1,0);
pthread_create(&id2,0,run2,0);
pthread_create(&id3,0,run3,0);
pthread_create(&id4,0,run4,0);
pthread_join(id1,0);
pthread_join(id2,0);
// pthread_join(id3,0);
// pthread_join(id4,0);
pthread_detach(id3);
pthread_detach(id4);
return 0;
}
第三题:
将函数封装成静态库,并测试,描述该函数的功能
功能是将键盘输入的字符转换成ASCII码并输出
#include <termios.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <assert.h>
int getch(){
int c=0;
struct termios org_opts, new_opts;
int res=0;
res=tcgetattr(STDIN_FILENO, &org_opts);
assert(res==0);
new_opts = org_opts;
new_opts.c_lflag &= ~(ICANON | ECHO | ECHOE | ECHOK | ECHONL | ECHOPRT | ECHOKE | ICRNL);
tcsetattr(STDIN_FILENO, TCSANOW, &new_opts);
c=getchar();
res=tcsetattr(STDIN_FILENO, TCSANOW, &org_opts);
assert(res==0);
return c;
}
int getch();
int main(int argc, const char *argv[])
{
int i=getch();
printf("%d\n",i);
return 0;
}