如何用C++实现哲学家进餐问题

#include
#include
#include
#include
#include
#include
using namespace std;
//线程函数
unsigned int __stdcall philosopher( void * );
bool think( int );
bool eat( int );
void wait( int );
void print();
int count = 0; //用于记录输出的次数
string phil_state[ 5 ]; //哲学家状态(思考、等待、吃饭)
bool stick[ 5 ]; //筷子的状态(有没有人正在使用)
//临界区结构变量
CRITICAL_SECTION crout; //保证输出时不会竞争
CRITICAL_SECTION chopsticks[ 5 ]; //定义五个临界变量,代表五根筷子
//线程函数
unsigned int __stdcall philosopher( void *k )
{
int n = ( ( int * ) k )[ 0 ];
srand( time( NULL ) );
while( true )
{
think( n );
eat( n );
}
return n;
}
//思考
bool think( int k )
{
if( phil_state[ k ] == "waiting" )
return false;
else
{
phil_state[ k ] = "thinking";
print();
return true;
}
}
//吃饭
bool eat( int k )
{
//只有同时获得两根筷子才能吃饭,否则进入等待状态
if( stick[ k ] == true && stick[ (k + 1 ) % 5 ] == true )
{
EnterCriticalSection( chopsticks + k );//获得左边的筷子
stick[ k ] = false;
EnterCriticalSection( chopsticks + ( k + 1 ) % 5 );//获得右边的筷子
stick[ (k + 1 ) % 5 ] = false;
phil_state[ k ] = "eating";
print();
//释放临界区
stick[ (k + 1 ) % 5 ] = true;
stick[ k ] = true;
phil_state[ k ] = "thinking";
LeaveCriticalSection( chopsticks + ( k + 1 ) % 5 );//放下右边的筷子
LeaveCriticalSection( chopsticks + k );//放下左边的筷子
return true;
}
else
{
wait( k );
return false;
}
}
//等待
void wait(int k)
{
phil_state[ k ] = "waiting";
print();
}
//输出函数
void print()
{
EnterCriticalSection( &crout );
count ++;
cout << "The " << count << "th time : " << endl;
for( int i = 0; i < 5; i ++ )
cout << "Philosoper " << i + 1 << " is " << phil_state[ i ] << endl;
cout << endl;
Sleep( 3000 );
LeaveCriticalSection( &crout );
}
int main()
{
void * hthread[ 5 ];
int i;
unsigned int threadid[ 5 ];
int arg[ 5 ];
unsigned long retval;
//初始化哲学家和筷子的状态
for( int i = 0; i < 5; i ++ )
{
phil_state[ i ] = "thinking";
stick[ i ] = true;
}
//初始化临界变量
InitializeCriticalSection( &crout );
for(i=0;i<5;i++)
{
InitializeCriticalSection( chopsticks + i );
}
//创建五个哲学家线程
for( i = 0; i < 5;i ++ )
{
arg[ i ] = i;
hthread[i]=(void *)_beginthreadex(NULL,0,philosopher,(void *)(arg + i),0,threadid+i);
if( ( int ) hthread[ i ] == -1 ) //如果线程创建失败返回-1
{
cerr << "Create thread error :" << i <cerr << "Error code : "<< GetLastError() <}
}
retval = WaitForMultipleObjects( 5, hthread, true, INFINITE ); //等待多个线程
if( retval == WAIT_FAILED )
{
cerr << "Wait error,error code: "<< GetLastError() << endl;
}
for( i = 0; i < 5; i ++ )
{
if( CloseHandle( hthread[ i ] ) == false )
{
c

err << "Close thread error: " << i <cerr << "Error code: "<< GetLastError() <}
}
return 0;
}

相关文档
最新文档