实验2 处理机调度与死锁 (设计型实验)
在Linux操作系统下,用C语言设计相应算法,以实现 1)哲学家进餐问题(P48)的:
a)第一种解法:只允许4位哲学家同时去拿左边的筷子。 b)第三种解法:奇偶拿筷子法。
要求:
1)同时提交“电子”和“书面”实验报告。 2)提供源代码并给出运行结果。 提示: 1)
http://192.168.150.81/OS-program/thread-sync/Nconsumer-Nproducer-unlimitedBuffer.c
提供了无限缓冲区的消费者与生产者问题的实现,其中有semaphore、mutex 的创建、PV操作、释放的API样例。
2)http://192.168.150.81/OS-program/thread-sync/ 提供了一般线程创建的API样例。
3)在Linux命令提示符下,可用man 3p apiName的方法,阅读某个api的详解。
4)在FC5下,推荐采用gedit 编辑器用书写C代码。
5位哲学家吃饭问题(算法描述)
/*
设有5个哲学家,共享一张放有5把椅子的桌子,每人分得一把椅子,但是,桌子上共有5只筷子,在每人两边各放一只,哲学家们在肚子饥饿时才试图分两次
从两边拿起筷子就餐。
条件:
1)拿到两只筷子时哲学家才开始吃饭。
2)如果筷子已在他人手上,则该哲学家必须等他人吃完之后才能拿到筷子。
3)任一哲学家在自己未拿到两只筷子前却不放下自己手中的筷子。
试:
1)描述一 个保证不会出现两个邻座同时要求吃饭的通信算法。
2)描述一个即没有两个邻座同时吃饭,有没有饿死(永远拿不到筷子)的算法
*/
/* 以下是测试代码 。。。。*/
#include
#define SizeArray 5
typedef struct { int value; }Key;
typedef struct
{ int left; int right; int busy;
}Man;
int getkey( int *blpKey, int *blpMan, int *blpBusy ) /* had key return 0 . get key or no key(orther got) return 1 */
{
if( *blpKey )
{
if(*blpMan) { return 0; } else { return 1; }
} else {
*blpMan = 1; *blpKey = 1; ++(*blpBusy); return 1;
} }
Man aMan[SizeArray]; Key aKey[SizeArray];
#define NextAp ((ap+SizeArray+1)%SizeArray)
#define DGetRight(ap,NextAp) getkey( &(aKey[NextAp].value), \\
&(aMan[ap].right), \\
&(aMan[ap].busy))
/*上边的 \\不是 / 。。。!*/
#define DGetLeft(ap,NextAp) getkey( &(aKey[NextAp].value), \\
&(aMan[ap].left), \\ &(aMan[ap].busy))
int count; int main( void )
{ int ap; int i;
/*for( i=0 ; i < SizeArray ; ++i )
{
aMan[i].left = 0; aMan[i].right= 0; aMan[i].busy = 0; aKey[i].value= 0;
} */
/* test 1000 no. */ for( i=0; i<1000; ++i )
{
ap = rand() % SizeArray ; /*SizeArray = 5 ..this */ if ( aMan[ap].busy == 2 ) /* had 2 key ,down all !! */
{
++count; /*record had thing to eating */
aMan[ap].left = 0; aMan[ap].right= 0; aMan[ap].busy = 0; aKey[ap].value = 0; aKey[NextAp].value = 0;
} else {
if( ap % 2 )
{
if ( DGetRight(ap,ap) ) { continue;} else{ DGetLeft(ap,NextAp) ;continue;}
} else {
if ( DGetLeft(ap,NextAp)) { continue;} else{ DGetRight(ap,ap) ;continue; }
} } } /*end for.. */
printf('dream : test = %d : %d ',500,count);
return 0; } /*end main..*/
哲学家吃饭问题算法C
![](/skin/haowen/images/icon_star.png)
![](/skin/haowen/images/icon_star.png)
![](/skin/haowen/images/icon_star.png)
![](/skin/haowen/images/icon_star.png)