Professional Documents
Culture Documents
PROGRAMMING
Independent process.
Co-operating process.
Though one can think that those processes, which are running independently,
will execute very efficiently, in reality, there are many situations when co-
operative nature can be utilised for increasing computational speed,
convenience and modularity.
import multiprocessing
import time
result = []
def square_list(mylist):
global result
# append squares of mylist to global list result
for num in mylist:
result.append(num * num)
# print global list result
print("Result(in process p1)",result)
time.sleep(1)
PYTHON ADVANCED PROGRAMMING
if __name__ == "__main__":
# input list
mylist = [1,2,3,4]
# creating new process
p1 = multiprocessing.Process(target=square_list,
args=(mylist,))
# starting process
p1.start()
# wait until process is finished
p1.join()
# print global result list
print("Result(in main program)",result)
When the above program is executed the output is
available only in the childs address space.
So modify the above program such that the output is
available in both child and parents address space
PYTHON ADVANCED PROGRAMMING
import multiprocessing
def square_list(mylist, result, square_sum):
# append squares of mylist to result array
for idx, num in enumerate(mylist):
result[idx] = num * num
# square_sum value
square_sum.value = sum(result)
if __name__ == "__main__":
# input list
mylist = [1,2,3,4]
# creating Array of int data type with space for 4 integers
result = multiprocessing.Array('i', 4)
# creating Value of int data type
square_sum = multiprocessing.Value('i')
# print(square_sum)
# creating new process
p1 = multiprocessing.Process(target=square_list, args=(mylist, result,
square_sum))
# starting process
p1.start()
# wait until process is finished
p1.join()
# print result array
print("Result(in main program):",result[:])
# print square_sum Value
print("Sum of squares(in main program):",square_sum.value)
THANK YOU
What is multiprocessing?
Why multiprocessing?
import multiprocessing
def print_cube(num):
print("Cube of a number is",num * num * num)
def print_square(num):
print("squre of a number is",num * num)
if __name__ == "__main__":
# creating processes
p1 = multiprocessing.Process(target=print_square, args=(10, ))
p2 = multiprocessing.Process(target=print_cube, args=(10, ))
# starting process 1
p1.start()
# starting process 2
p2.start()
# wait until process 1 is finished
p1.join()
# wait until process 2 is finished
p2.join()
# both processes finished
print("Done!")
PYTHON ADVANCED PROGRAMMING
# starting processes
p1.start()
p2.start()
# wait until processes are finished
p1.join()
p2.join()
# both processes finished
print("Both processes finished execution!")
# check if processes are alive
print("p1 status is alive?:",p1.is_alive())
print("p2 status is alive?:",p2.is_alive())
THANK YOU
What is multiprocessing?
Why multiprocessing?
import multiprocessing
def print_cube(num):
print("Cube of a number is",num * num * num)
def print_square(num):
print("squre of a number is",num * num)
if __name__ == "__main__":
# creating processes
p1 = multiprocessing.Process(target=print_square, args=(10, ))
p2 = multiprocessing.Process(target=print_cube, args=(10, ))
# starting process 1
p1.start()
# starting process 2
p2.start()
# wait until process 1 is finished
p1.join()
# wait until process 2 is finished
p2.join()
# both processes finished
print("Done!")
PYTHON ADVANCED PROGRAMMING
# starting processes
p1.start()
p2.start()
# wait until processes are finished
p1.join()
p2.join()
# both processes finished
print("Both processes finished execution!")
# check if processes are alive
print("p1 status is alive?:",p1.is_alive())
print("p2 status is alive?:",p2.is_alive())
THANK YOU
def fn1() :
s = 'ABCDEFGH'
for i in range(0, len(s)) :
lock.acquire()
print(s[i], end=' ')
sys.stdout.flush()
time.sleep(int(random.random() * 3))
print(s[i], end=' ')
sys.stdout.flush()
lock.release()
time.sleep(int(random.random() * 3))
PYTHON ADVANCED PROGRAMMING
def fn2() :
s = 'abcdefgh'
for i in range(0, len(s)) :
lock.acquire()
print(s[i], end=' ')
sys.stdout.flush()
time.sleep(int(random.random() * 3))
print(s[i], end=' ')
sys.stdout.flush()
lock.release()
time.sleep(int(random.random() * 3))
THANK YOU
def fn1() :
s = 'ABCDEFGH'
for i in range(0, len(s)) :
lock.acquire()
print(s[i], end=' ')
sys.stdout.flush()
time.sleep(int(random.random() * 3))
print(s[i], end=' ')
sys.stdout.flush()
lock.release()
time.sleep(int(random.random() * 3))
PYTHON ADVANCED PROGRAMMING
def fn2() :
s = 'abcdefgh'
for i in range(0, len(s)) :
lock.acquire()
print(s[i], end=' ')
sys.stdout.flush()
time.sleep(int(random.random() * 3))
print(s[i], end=' ')
sys.stdout.flush()
lock.release()
time.sleep(int(random.random() * 3))
THANK YOU
SQLite3
SQLite3
SQLite3
Connection objects
Connection objects create a connection with the database and
these are further used for different transactions. These connection
objects are also used as representatives of the database session.
You can use a connection object for calling methods like commit(),
rollback() and close()
Cursor objects
Cursor is one of the powerful features of SQL. These are objects
that are responsible for submitting various SQL statements to a
database server.
PYTHON APPLICATION PROGRAMMING
Database Programming
Sample Program:
import sqlite3
cxn=sqlite3.connect("example.db")
cur=cxn.cursor()
''' #execute first and then comment
cur.execute('create table tab1 (name char(20), age integer)')
cur.execute('create table tab2 (name char(20), age integer)')
'''
PYTHON APPLICATION PROGRAMMING
Database Programming
Sample Program(continued):
cur.execute('insert into tab1 values ("chitra",34)')
cur.execute('insert into tab1 values ("rama",34)')
cxn.execute('insert into tab2 values ("Ganesh",21)')
cxn.execute('insert into tab2 values ("Ggg",21)')
#usage of place holder.
info=('aa',30)
cur.execute('insert into tab1 (name,age) values (?,?)',info)
x=cur.execute('select * from tab1')
for i in x:
print(i)
print("done")
THANK YOU
chitragm@pes.edu
+91 9900300411
pramadevi@pes.edu
+91 9620072112
PYTHON ADVANCED
PROGRAMMING
Class semaphore([value])
The optional argument gives the initial value for the internal
counter; it defaults to 1.
PYTHON ADVANCED PROGRAMMING
acquire([blocking])
Acquire a semaphore.
release()
import threading
from time import sleep
sem = threading.Semaphore()
def fun1():
print("fun1 starting")
sem.acquire()
for loop in range(1,5):
print("Fun1 Working in loop")
sleep(1)
sem.release()
print("fun1 finished")
PYTHON ADVANCED PROGRAMMING
def fun2():
print("fun2 starting")
while not sem.acquire(blocking=False):
print("Fun2 No Semaphore available")
sleep(1)
else:
print("Got Semphore")
for loop in range(1, 5):
print("Fun2 Working loop too")
sleep(1)
sem.release()
PYTHON ADVANCED PROGRAMMING
t1 = threading.Thread(target = fun1)
t2 = threading.Thread(target = fun2)
t1.start()
t2.start()
t1.join()
t2.join()
print("All Threads done Exiting")
PYTHON ADVANCED PROGRAMMING
# That's all fine, but you can also release it without acquiring
it first.
s1.release()
s2 = BoundedSemaphore(5) # Start at 5.
s2.acquire() # Lower to 4.
s2.release() # Go back to 5.
print(s2._value)
try:
s2.release() # Try to raise to 6, above
starting value.
print(s2._value)
except ValueError:
print('As expected, it complained.')
THANK YOU