Commands:
mongo
>use test
> db.getCollectionNames()
> db.collection.find()
>exit
python
>import pymongo
>pymongo.version
File: dini_prac2.py
from pymongo import MongoClient
import threading
from threading import Thread
import time
class Philosophers(Thread):
connection=MongoClient("localhost",27017)
def read_mongo(self,indexx):
db=Philosophers.connection.test.diniraw7 #Philosophers.connection.DB.coll_name
cursor=db.find({"ph_no":indexx})
print cursor[0]
def __init__(self,indexx,name,leftFork,rightFork):
Thread.__init__(self)
self.name=name
self.indexx=indexx
self.leftFork=leftFork
self.rightFork=rightFork
def run(self):
while(self.running==True):
#note: self.running !
#thinking
time.sleep(6)
print 'Philosopher %d is hungry '%self.indexx
self.get_fork()
def get_fork(self):
fork1=self.leftFork
fork2=self.rightFork
while(self.running==True):
fork1.acquire(True)
val=fork2.acquire(False)
if val:
break
fork1.release()
#if not got 2nd fork,release first fork
fork1,fork2=fork2,fork1
#swap
else:
return
self.dine()
fork1.release()
fork2.release()
def dine(self):
print "Philosopher %d is finally eating"%self.indexx
self.read_mongo(self.indexx)
time.sleep(5)
print "Philosopher %d is finally finished eating"%self.indexx
def Dining():
fork=[]
for i in range (5):
fork.append(threading.Lock())
names=("a","b","c","d","e")
phils=[]
for i in range(5):
phils.append(Philosophers(i,names[i],fork[i%5],fork[(i+1)%5]))
Philosophers.running=True
#note: Philosophers.running !
for p in phils:
p.start()
time.sleep(30)
print "Finishing!"
Philosophers.running=False
Dining()
File: load_data.py
from pymongo import MongoClient
f=open('data.txt').read().strip().split("\n")
connection=MongoClient("localhost",27017)
db=connection.test.diniraw7
for line in f:
record=line.strip().split(",")
post={"ph_no":int(record[0]),"temp":int(record[1])}
db.insert(post)
File: data.txt
0,99
1,23
2,34
3,45
4,11
5,12
Output
[amodi@localhost a4]$ python load_data.py
[amodi@localhost a4]$ python dini_prac2.py
Philosopher 0 is hungry
Philosopher 0 is finally eating
Philosopher 1 is hungry
Philosopher 2 is hungry
Philosopher 2 is finally eating
Philosopher 4 is hungry Philosopher 3 is hungry
{u'ph_no': 0{u'ph_no': 2, u'_id': ObjectId('570f5668e138230f2295c598'), u'temp': 34}, u'_id': ObjectId('570f5668e138230f2295c596'), u'temp': 99}
Philosopher 2 is finally finished eating
Philosopher 0 is finally finished eating
Philosopher 1 is finally eating
Philosopher 3 is finally eating
{u'ph_no': 1, u'_id': ObjectId('570f5668e138230f2295c597'), u'temp': 23}
{u'ph_no': 3, u'_id': ObjectId('570f5668e138230f2295c599'), u'temp': 45}
Philosopher 1 is finally finished eating
Philosopher 3 is finally finished eating
Philosopher 4 is finally eating
{u'ph_no': 4, u'_id': ObjectId('570f5668e138230f2295c59a'), u'temp': 11}
Philosopher 2 is hungry
Philosopher 2 is finally eating
Philosopher 0 is hungry
{u'ph_no': 2, u'_id': ObjectId('570f5668e138230f2295c598'), u'temp': 34}
^Z
[1]+ Stopped python dini_prac2.py