Monday, May 9, 2011

IGNOU MCSL-045 Lab Manual Solution



Session 1
SQL> select * from teacher
  2  /
T_NO F_NAME     L_NAME                        SALARY SUPERVISOR                     JOININGDA BIRTHDATE TITLE
---------- ------------------------- ------------------------- ---------- ------------------------------ --------- --------- ----------
         1 faraz               ahmad                             22000 Arshad Iqbal                   25-JAN-10 25-MAY-86 Primary
         2 Jaideep                   Sharma                23000 Asim Zafar                     23-JUN-09 04-APR-86 PRT
         3 zakir                     Ali                           22000 Asim Zafar                     03-DEC-09 24-AUG-87 PGT
         4 Shaista                   Khan                     23500 Arshad Iqbal                   03-MAY-10 23-JUL-86 PRT
Asma                  Husain                    21300 Aqeel Ahmad                    24-MAY-10 20-NOV-84 Primary
Display the name of the teacher(s) who is (are) the youngest among all the teachers.

SQL> select f_name, l_name
  2  from teacher
  3  where birthdate=(select max(birthdate) from teacher)
  4  ;
F_NAME                    L_NAME
------------------------- -------------------------
zakir                     Ali
b) Display details of all the teachers who have the same job title as that of ‘Jaideep’
 1  select * from teacher
  2* where title=(select title from teacher where LOWER(f_name)='jaideep')
SQL> /



  T_NO   F_NAME                      L_NAME      SALARY SUPERVISOR                     JOININGDA BIRTHDATE TITLE
----------  ------------------------- ------------------------- ---------- ------------------------------ --------- --------- ----------
    2       Jaideep                   Sharma                         23000 Asim Zafar                     23-JUN-09 04-APR-86 PRT
         4 Shaista                   Khan                           23500 Arshad Iqbal                   03-MAY-10 23-JUL-86 PRT

e) Identify all those teachers who are in grade ‘B’.

 select distinct *from teacher,payscale
 where grade='B'
 /
T_NO F_NAME      L_NAME             SALARY SUPERVISOR                JOININGDA BIRTHDATE TITLE      GRADE
------ --------------  ------------------------- ---------- ------------------------------ --------- --------- ---------- -----
     5 Asma                 Husain              21300 Aqeel Ahmad                    24-MAY-10 20-NOV-84 Primary    B      
     7 naim                      ahmad         29000 Arshad Iqbal                         15-AUG-05 16-MAY-80 PGT        B      
     2 Jaideep                   Sharma       23000 Asim Zafar                     23-JUN-09 04-APR-86 PRT        B      
     1 faraz                     ahmad            22000 Arshad Iqbal                   25-JAN-10 25-MAY-86 Primary    B      
4 rows selected.

g) Display the names of all teachers who are supervisors.

  1  select * from teacher
  2* where teacher.supervisor='jaideep'
SQL> /
  T_NO F_NAM    L_NAME     SALARY SUPERVISOR                     JOININGDA BIRTHDATE TITLE
--------- -------------------- ------------------------- ---------- ------------------------------ --------- --------- ----------
     arshi                     khan     14000 jaideep                        12-MAR-09 15-OCT-87 PRT

f) Display the names and numbers of all teachers who are class teachers and are in grade ‘C’.


 1  select t_no,f_name
 2  from teacher t, payscale p
 3  where p.grade='C' AND t.salary =(select salary from teacher
 4*  where salary BETWEEN '10000'  AND '17999')
QL> /
     T_NO F_NAME
--------- -------------------------
Arshi
Display details of all those teachers who are class teachers of classes 1 to 5.

SQL> select f_name,l_name, class_no
  2  from teacher, class
  3  where teacher.t_no=class.t_no(+);

F_NAME                    L_NAME                      CLASS_NO
------------------------- ------------------------- ----------
faraz                        ahmad                              5
Jaideep                   Sharma                             8
zakir                        Ali                                      9
Shaista                     Khan                               6
Asma                      Husain                             3
Q3)
Design a suitable database system for a bank along with 20 possible queries to the database (the queries should be such that their solution involves subqueries or joins or both). Implement the database and the queries in a commercial DBMS using SQL.
Bank database
 1  create table acco_master (accno number(10) primary key,name
  2* varchar2(10),balance number(10))
SQL> /
Table created.
SQL>insert into acco_master values(&accno,'&name',&balance)
Enter value for accno:111
Enter value for name:faraz
Enter value for balance:200000
SQL>create table acco_trans(accno number(10),trans_date date,deb_cre                     
varchar2(10),check(deb_cre IN('debit','credit')),amount number(10),  process varchar2(10)
check(process IN('yes','no')) foreign key  (accno)references acco_master);
                   Table Created
SQL> insert into acco_trans values(&accno,'sysdate,'&deb_cre',&amount,                     
'&process');                
 Enter value for accno:111
Enter value for deb_cre:debit
Enter value for amount:1000
Enter value for process:yes

SESSION 2
Display teacher number, their names, age and grade of all PGT teachers.
SELECT t_no, name, age, grade
FROM teacher_details
WHERE UPPER (title) = ‘PGT’;
b) Create a non-unique index on the foreign key column of the ‘class’ table.

SQL> create index class
  2  on class(t_no, room_no);
Index created.
g) Create a non-unique index on the names of teachers in the ‘teachers’ table.

SQL> create index t_name
  2  on teacher (f_name, l_name)
  3  /
Index created.
h) Drop the index created in (b).
SQL> drop index class
  2  /
Index dropped.
j) Display details of all the teachers who are more than 40 years old.
SELECT t_no, name, salary, title, age
FROM teacher_details
WHERE age > 40;
No row selected.


Session 3
(a) Calculate the bonus amount to be given to a teacher depending on the following conditions:
I. if salary > 10000 then bonus is 10% of the salary.
II. if salary is between 10000 and 20000 then bonus is 20% of the salary.
III. if salary is between 20000 and 25000 then bonus is 25% of the salary.
IV. if salary exceeds 25000 then bonus is 30% of the salary.

  create or replace procedure bonus_calc integer
  (o_t_no IN INTEGER, bonus OUT INTEGER)
  is
  salary INTEGER
  BEGIN
  select salary, f_name, l_name,bonus
  from teacher
  where t_no= o_t_no
  IF salary> 10000
  then bonus:= salary+ salary* 0.10
  END IF
  IF salary between 10000 and 20000
  then bonus:= salary + salary * 0.20
  END IF
  IF salary between 20000 and 25000
  then bonus:= salary + salary * 0.25
  END IF
  IF salary between 25000 and 30000
  then bonus:= salary + salary * 0.30
  END IF
 END
Procedure successfully Created!
Exec bonus_calc

    SALARY F_NAME                    L_NAME                         BONUS
---------- ------------------------- -------------------------       -------------------------
      22000   faraz                     ahmad                                5500
     23000   Jaideep                   Sharma                             5750
     22000   zakir                       Ali                                         5500
     23500   Shaista                   Khan                                  5875
     21300   Asma                      Husain                              5325
     14000   arshi                     khan                                   2800
     29000   naim                      ahmad                              8700
 (h) Calculate the tax to be paid by all teachers depending on following conditions:
I. if annual salary > 1,00,000 then no tax.
II. if annual salary is between 1,00,001 and 1,50,000 then tax is 20% of the annual salary.
III. if annual salary is between 1,50,001 and 2,50,000 then tax is 30% of the annual salary.
IV. if salary exceeds 2,50,000 then tax is 40% of the annual salary.
    create or replace procedure tax_calc integer
    (o_t_no IN INTEGER, tax OUT INTEGER)
    is
    salary INTEGER
    BEGIN
    select f_name, l_name,tax
    from teacher
    where t_no= o_t_no
    IF salary<100000
    salary=salary*12
    then tax:=0
    END IF
    IF salary between 100001 and 150000
    then tax:= salary * .20
    END IF
    IF salary between 150001 and 250000
    then tax:= salary * .30
    END IF
    IF salary >250001
    then tax:= salary * .40
*   END IF
Procedure created successfully!
Exec tax_calc
      T_NO F_NAME                    L_NAME                        SALARY          TAX
      --------- ------------------------- -------------------------       ----------     ----------
         1 faraz                          ahmad                                     22000              105600
        2 Jaideep                            Sharma                          23000               110400
        3 zakir                           Ali                                                22000                 105600
        4 Shaista                              Khan                           23500                 112800
        5 Asma                                 Husain                         21300                102240
        6 arshi                                   khan                              14000                   50400
        7 naim                                ahmad                         29000                  139200

Q3)Implement at least five procedures for the Bank Database system using embedded SQL.
SQL>set serveroutput on
SQL>declare
cursor c_bank is select * from acco_trans;
 v_bank c_bank%rowtype;
 balance number(5);
 begin
open c_bank;
loop
fetch c_bank into v_bank;
exit when c_bank%notfound;
if v_bank.process='no' then                                                                   
update acco_trans set process='yes' where
accno=v_bank.accno;
if v_bank .deb_cre='credit' then
update acco_master set balance=balance+v_bank.amount
where    v_bank.accno=acco_master.accno;
elsif v_bank.deb_cre='debit' then 
update acco_master set balance=balance-v_bank.amount
where    v_bank.accno=acco_master.accno;
elsif balance<=0 then
dbms_output.put_line('Transaction not possible');
end if;
end if;
end loop; 
close c_bank;
end;
SQL>select * from acco_trans;                  
AccNo  Trans_Date       Deb_Cre        Amt  Pro
----------  -------------- ------------    --------- --------------
1012        12-Jan-08    debit           5000    yes
1024       14-Feb-08    credit                100        yes
1987        04-Dec-07   credit         1000      yes
2345         17-Mar-08  credit        20000     yes
Cursor for BANK DATABASE
SQL >  create table depositor (accno primary key , cname char(10))
Table created.
SQL >  create table borrower  (loanno  number , cname char(10))
Table created.
SQL >  create table loan( loanno number , brname char(10),amt number)
Table created.
SQL >  create table acct-t( acctno number , bal number, brname char(10), foreign key (acctno)
references depositor (acctno)
Table created.
SQL >  insert into   depositor  values (&accno  , &cname );
Enter value for accno        : 101
Enter the value for cname : Alan
SQL >  insert into   acct-t  values( &acctno  , &bal , '&brname ');
Enter value for accno        : 101
Enter the value for bal      : 20000
Enter the value for brname : tvm
SQL > select * from depositor;
ACCNO               CNAME
    101                    Alan
102                    Ann
103                    Ben
SQL > select * from acct-t;
ACCNO               BAL               BRNAME
-------------    -------------------   ----------------
101                    20000                tvm      
102                    10500                 ekm
103                    5000                    tcr
SQL >   create or replace trigger
declare
   c varchar2 (20)
begin
if (:new.bal < :old.bal) then
 insert into loan values (:new.accno, :new.brname , :old.bal-:new.bal);
select cname into c from depositor where accno = new.accno;
insert into borrower values (:new.accno,c);
endif;
end;
/
Trigger created.
SQL > update acct-t set bal = bal-5000 where acctno=101
1 row updated.
SQL >select * from borrower;
LOANNO              CNAME
--------------       --------------------
101                           Alan
SQL >select * from loan;
LOANNO          BR NAME             AMT
101                         tvm                  15000 
SESION 4
Write a host language block to delete all the rows from the ‘teacher’ table where the salary is less than Rs.5000.
DECLARE
c_t_no teacher.t_no%TYPE;
c_f_name teacher.f_name%TYPE;
c_l_name teacher.l_name%TYPE;
c_salary teacher.salary%TYPE;
CURSOR c1 IS
SELECT t_no,f_name, l_name, salary
FROM teacher;
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO c_t_no, c_f_name, c_l_name, c_salary ;
EXIT WHEN NOT c1%FOUND;
UPDATE teacher SET salary = salary * 1.10 WHERE salary < 5000;
END LOOP;
CLOSE c1;
END;
2) Write a host language code to insert the supervisor information from ‘teacher’ table to another table called ‘supervisor’. The new table should have only those records where the job title is ‘supervisor’.
DECLARE
CURSOR c2 IS
SELECT t_no,f_name, l_name, salary
FROM teacher ;
teacher_rec c2%ROWTYPE;
BEGIN
OPEN c2;
FOR teacher_rec IN c2
LOOP
IF teacher_rec.salary > 20000
Teacher_rec.title = “SUPERVISOR”;
ENDIF;
END LOOP;
CLOSE c2;
END;
SESSION 5
1) Write a function that gets the teacher id as parameter and returns the class number associated with that teacher. If the teacher is not a class teacher then give suitable message.

DECLARE
C_id teacher.t_no%TYPE;
C_f_name teacher.f_name%TYPE;
want_id NUMBER := 110;
BEGIN
SELECT t_no, f_name INTO c_t_no, c_f_name from teacher
WHERE t_no = want_id;
DBMS_OUTPUT.PUTLINE ( “teacher : “|| c_t_no ||’ ‘||c_f_name)
EXCEPTION
WHEN INVALID_NUMBER THEN
DBMS_OUTPUT.PUTLINE(want_id || ‘ not a valid teacher id’);
END;
CREATE OR REPLACE TRIGGER new_teacher _id
AFTER INSERT ON teacher
FOR EACH ROW
DECLARE
o_t_no teacher.t_no%TYPE;
o_joiningdate teacher.joiningdate%TYPE;
BEGIN
SELECT t_no_sequence.nextval
INTO o_t_no
FROM dual;
:NEW.t_no := o_t_no;
:NEW.joiningdate := SYSDATE;
END;
Session 6
Find the grade of teachers.
CREATE OR REPLACE FUNCTION get_grade (o_t_no IN NUMBER)
IS o_grade VARCHAR2(20);
BEGIN
SELECT grade INTO o_grade FROM Payscale, teacher
WHERE t_no = o_t_no AND salary between min_limit AND max_limit;
RETURN (o_grade);
END get_grade;
Exercise 8
1) Add a nested table in the teacher relation. Do some queries using nested tables?
Ans.)
CREATE TABLE student_credits
(rollno  NUMBER(5),
s_name VARCHAR2(25),
subject_credits  NEW_TYPE)
NESTED TABLE subject_credits STORE AS new_type_table;
INSERT INTO student_credits
VALUES (100, ‘suman’ , new_table ( new_type (‘english’ , 30),
                                         new_table ( new_type(‘hindi’, 35)));
SELECT  s.credit_hours FROM
    THE (SELECT subjects_credit FROM student_credits
                WHERE s_name = ‘suman’)  s
WHERE s.subject_name = ‘english’;
Q2) Create at least two nested tables for both the University and Bank database
systems. Use these tables and enter some data into these relations. Query these
databases.

CREATE TYPE address_t AS OBJECT (
street VARCHAR2(30),
city VARCHAR2(20),
state CHAR(2),
zip CHAR(5) );
/
CREATE TYPE address_tab IS TABLE OF address_t;
/
CREATE TABLE customers (
custid NUMBER,
address address_tab )
NESTED TABLE address STORE AS customer_addresses;

INSERT INTO customers VALUES (1,
address_tab(
address_t('101 First', 'Redwood Shores', 'CA', '94065'),
address_t('123 Maple', 'Mill Valley', 'CA', '90952')
) );
Exercise 9
Q1) Identify the use of large object types in the teacher’s table. Do some queries
using these objects.
Ans
CREATE TABLE message (
    msg_id  NUMBER(8) NOT NULL PRIMARY KEY,
        email_add       VARCHAR(200),
        name            VARCHAR (200),
        message         CLOB,
        posting_time    DATE,
        sort_key        VARCHAR (600));
DECLARE
Image10          BLOB;
  image_number     INTEGER := 101;
BEGIN 
  SELECT item_blob INTO image10 FROM lob_table10
      WHERE key_value = image_number;
  DBMS_OUTPUT.PUT_LINE('Image size
is:'||DBMS_LOB.GETLENGTH(image10));
 ------   
 ------   
  ------   
END;
Exercise 10
Q1) Create a user account “class” and give privileges related to table/view creation,
deletion, updating and dropping.
Ans
CREATE USER class 
IDENTIFIED BY pass;
GRANT  CREATE TABLE, DROP TABLE, CREATE VIEW, DROP VIEW 
TO  class;
Q. 2) Create a student account and give permission to this account for only viewing
the information on the relation Class (class_no, t_no, room_no.
Ans
DENY UPDATE, DELETE, INSERT ON employee TO student
GO
CREATE USER student
  @Eclass_no int,
  @St_no money,
  @room_no int
GRANT EXECUTE ON student TO Class
GO




Wednesday, April 6, 2011

FOR SOLUTION TO ANY IGNOU PROBLEM YOU MAY CLICK THIS LINK

Tuesday, March 22, 2011

solution to MCS 043 DATABASE MANAGEMENT SYSTEM


4a)i)
Ans.
A knowledge base (abbreviated KB, kb ) is a special kind of database for knowledge management, providing the means for the computerized collection, organization, and retrieval of knowledge. Also a collection of data representing related experiences, their results are related to their problems and solutions.
The knowledge based systems are artificial intelligent tools working in a narrow domain to provide intelligent decisions with justification. Knowledge is acquired and represented using various knowledge representation techniques rules, frames and scripts. The basic advantages offered by such system are documentation of knowledge, intelligent decision support, self learning, reasoning and explanation


Question 4)a)ii)
Ans.

A mobile database is a database that can be connected to by a mobile computing device over a mobile network. The client and server have wireless connections. A cache is maintained to hold frequent data and transactions so that they are not lost due to connection failure. A database is a structured way to organize information. This could be a list of contacts, price information or distance travelled.[1]
The use of laptops, mobiles and PDAs is increasing and likely to increase in the future[citation needed] with more and more applications residing in the mobile systems. While those same analysts can’t tell us exactly which applications will be the most popular, it is clear that a large percentage will require the use of a database of some sort. Many applications such as databases would require the ability to download information from an information repository and operate on this information even when out of range or disconnected.
An example of this is a mobile workforce. In this scenario user would require to access and update information from files in the home directories on a server or customer records from a database. This type of access and work load generated by such users is different from the traditional workloads seen in client–server systems of today. With the advent of mobile databases, now users can load up their smart phones or PDAs with mobile databases to exchange mission-critical data remotely without worrying about time or distance. Mobile databases let employees enter data on the fly. Information can be synchronized with a server database at a later time.
Question 4)a)iii)
Ans.
A digital library is a library in which collections are stored in digital formats (as opposed to print, microform, or other media) and accessible by computers. The digital content may be stored locally, or accessed remotely via computer networks. A digital library is a type of information retrieval system.
The DELOS Digital Library Reference Model defines a digital library as:
An organization, which might be virtual, that comprehensively collects, manages and preserves for the long term rich digital content, and offers to its user communities specialized functionality on that content, of measurable quality and according to codified policies.

Question 4)a)iv)
Ans.
A spatial database is a database that is optimized to store and query data related to objects in space, including points, lines and polygons. While typical databases can understand various numeric and character types of data, additional functionality needs to be added for databases to process spatial data types. These are typically called geometry or feature. The Open Geospatial Consortium created the Simple Features specification and sets standards for adding spatial functionality to database systems.

Question 4) b) i).
Ans.
An index is a performance-tuning method of allowing faster retrieval of records. An index creates an entry for each value that appears in the indexed columns. By default, Oracle creates B-tree indexes.

Create an Index

The syntax for creating a index is:
CREATE [UNIQUE] INDEX index_name
  ON table_name (column1, column2, . column_n)
  [ COMPUTE STATISTICS ];

Monday, March 14, 2011

Monday, February 21, 2011

MCS 042- Question 3: (a) Discuss how fragmentations manifest itself in each of the following types of virtual storage system. i) Segmentation


Segmented virtual memory

Some systems, such as Burroughs B5500,do not use paging to implement virtual memory. Instead, they use segmentation, that divide virtual address spaces into variable-length segments. A virtual address consists of a segment number and an offset within the segment.
Notably, the Intel 80286 supports a similar segmentation scheme as an option, but it is little used.
It is possible to combine segmentation and paging, dividing each segment into pages. In systems that combine them, such as Multics, IBM System/38 and IBM System i machines, virtual memory is usually implemented with paging, with segmentation providing memory protection.
In the Intel 80386 and later IA-32 processors, the segments reside in a 32-bit linear, paged address space. Segments can be moved in and out of that space, and pages in that space can "page" in and out of main memory, providing two levels of virtual memory; however, few if any operating systems do so. Instead, they use only paging. Early x86 virtualization solutions (non-hardware-assisted) combined paging and segmentation because x86 paging offers only two protection domains, whereas a VMM / guest OS / guest applications stack (typically running on rings 0 / 1 / 3) needs three memory protection domains.
The difference between paging and segmentation systems is not only about memory division. In Multics, System/38 and Prime machines, segmentation is visible to user processes, as part of memory model semantics. In other words, instead of memory that looks like a single large vector, memory is structured into multiple spaces.
This difference has important consequences; a segment isn't just a "page with a variable length", or a simple way to lengthen the address space (as in Intel 80286). In Multics, segmentation that can provide a single-level memory model, in which there is no differentiation between "process memory" and "file system". I.e., a process's active address space for both code and data consists of only a list of segments (files) which are mapped into the process's potential address space.
This is not the same as the mechanisms provided in TENEX and TOPS-20 (PMAP), modern Unix-like systems (mmap), and Win32 systems (MapViewOfFile), because inter-file pointers don't work when mapping files into semi-arbitrary places. In Multics, a file (or a segment from a multi-segment file) is mapped into a segment in the address space, so files are always mapped at a segment boundary. A file's linkage section can contain pointers that are "unsnapped links"; an attempt to load the pointer into a register or make an indirect reference through it causes a trap (a field in the pointer can have a value that specifies that an attempt to dereference it should cause a trap). The unresolved pointer contains an indication of the name of the segment to which the pointer refers, and an offset within the segment; the handler for the trap will "snap the link" the pointer by mapping the segment into the address space, putting the segment number into the pointer, and changing the tag field in the pointer so that it no longer causes the trap), and return to the code where the trap occurred, re-executing the instruction that caused the trap. This eliminates the need for a linker completely. This also works when different processes map the same file into different places in their private address spaces.

MCS 042 Question 2: Write a semaphore based solution to Dining Philosopher problem and explain all the assumptions and the algorithm.

The dining philosophers problem is summarized as five philosophers sitting at a table doing one of two things: eating or thinking. While eating, they are not thinking, and while thinking, they are not eating. The five philosophers sit at a circular table with a large bowl of spaghetti in the center. A fork is placed in between each pair of adjacent philosophers, and as such, each philosopher has one fork to his left and one fork to his right. As spaghetti is difficult to serve and eat with a single fork, it is assumed that a philosopher must eat with two forks. Each philosopher can only use the forks on his immediate left and immediate right.

philosophers problem
The dining philosophers problem is sometimes explained using rice and chopsticks rather than spaghetti and forks, as it is more intuitively obvious that two chopsticks are required to begin eating.
The philosophers never speak to each other, which creates a dangerous possibility of deadlock when every philosopher holds a left fork and waits perpetually for a right fork (or vice versa).
Originally used as a means of illustrating the problem of deadlock, this system reaches deadlock when there is a 'cycle of unwarranted requests'. In this case philosopher P1 waits for the fork grabbed by philosopher P2 who is waiting for the fork of philosopher P3 and so forth, making a circular chain.
Starvation (and the pun was intended in the original problem description) might also occur independently of deadlock if a philosopher is unable to acquire both forks because of a timing problem. For example there might be a rule that the philosophers put down a fork after waiting five minutes for the other fork to become available and wait a further five minutes before making their next attempt. This scheme eliminates the possibility of deadlock (the system can always advance to a different state) but still suffers from the problem of livelock. If all five philosophers appear in the dining room at exactly the same time and each picks up the left fork at the same time the philosophers will wait five minutes until they all put their forks down and then wait a further five minutes before they all pick them up again.
In general the dining philosophers problem is a generic and abstract problem used for explaining various issues which arise in problems which hold mutual exclusion as a core idea. The various kinds of failures these philosophers may experience are analogous to the difficulties that arise in real computer programming when multiple programs need exclusive access to shared resources. These issues are studied in the branch of Concurrent Programming. The original problems of Dijkstra were related to external devices like tape drives. However, the difficulties studied in the Dining Philosophers problem arise far more often when multiple processes access sets of data that are being updated. Systems that must deal with a large number of parallel processes, such as operating system kernels, use thousands of locks and synchronizations that require strict adherence to methods and protocols if such problems as deadlock, starvation, or data corruption are to be avoided.

Monitor solution

The example below shows a solution where the forks are not represented explicitly. Philosophers can eat if neither of their neighbors are eating. This is comparable to a system where philosophers that cannot get the second fork must put down the first fork before they try again.
In the absence of locks associated with the forks, philosophers must ensure that the decision to begin eating is not based on stale information about the state of the neighbors. E.g. if philosopher B sees that A is not eating, then turns and looks at C, A could begin eating while B looks at C. This solution avoids this problem by using a single mutual exclusion lock. This lock is not associated with the forks but with the decision procedures that can change the states of the philosophers. This is ensured by the monitor. The procedures testpickup and putdown are local to the monitor and share a mutual exclusion lock. Notice that philosophers wanting to eat do not hold a fork. When the monitor allows a philosopher who wants to eat to continue, the philosopher will reacquire the first fork before picking up the now available second fork. When done eating, the philosopher will signal to the monitor that both forks are now available.
Notice that this example does not tackle the starvation problem. For example, philosopher B can wait forever if the eating periods of philosophers A and C always overlap.
To also guarantee that no philosopher starves, one could keep track of the number of times a hungry philosopher cannot eat when his neighbors put down their forks. If this number exceeds some limit, the state of the philosopher could change to Starving, and the decision procedure to pick up forks could be augmented to require that none of the neighbors are starving.
A philosopher that cannot pick up forks because a neighbor is starving, is effectively waiting for the neighbor's neighbor to finish eating. This additional dependency reduces concurrency. Raising the threshold for transition to the Starving state reduces this effect.

Resource hierarchy solution

Another simple solution is achieved by assigning a partial order to the resources (the forks, in this case), and establishing the convention that all resources will be requested in order, and released in reverse order, and that no two resources unrelated by order will ever be used by a single unit of work at the same time. Here, the resources (forks) will be numbered 1 through 5, in some order, and each unit of work (philosopher) will always pick up the lower-numbered fork first, and then the higher-numbered fork, from among the two forks he plans to use. Then, he will always put down the higher numbered fork first, followed by the lower numbered fork. In this case, if four of the five philosophers simultaneously pick up their lower-numbered fork, only the highest numbered fork will remain on the table, so the fifth philosopher will not be able to pick up any fork. Moreover, only one philosopher will have access to that highest-numbered fork, so he will be able to eat using two forks. When he finishes using the forks, he will put down the highest-numbered fork first, followed by the lower-numbered fork, freeing another philosopher to grab the latter and begin eating.
This solution to the problem is the one originally proposed by Dijkstra.
While the resource hierarchy solution avoids deadlocks, it is not always practical, especially when the list of required resources is not completely known in advance. For example, if a unit of work holds resources 3 and 5 and then determines it needs resource 2, it must release 5, then 3 before acquiring 2, and then it must re-acquire 3 and 5 in that order. Computer programs that access large numbers of database records would not run efficiently if they were required to release all higher-numbered records before accessing a new record, making the method impractical for that purpose.