Monday, March 30, 2020

queue in python language

from threading import *
import time
import random
import queue

def produce(q):
    while True:
        item=random.randint(1,100)
        print("producer producing item",item)
        q.put(item)
        print("producer giving notification")
        time.sleep(5)

def consume(q):
    while True:
        print("consumer waiting for updation")
        print("consumer consuming items:",q.get())
        time.sleep(5)
     

q=queue.Queue()
t1=Thread(target=consume,args=(q,))
t2=Thread(target=produce,args=(q,))
t1.start()
t2.start()


example 2:

import queue
q=queue.Queue()#FIFO
q.put(10)
q.put(20)
q.put(15)
q.put(30)
q.put(0)
while not q.empty():
    print(q.get(),end=' ')

output:
10 20 15 30 0

example 3:

import queue
q=queue.LifoQueue()
q.put(10)
q.put(20)
q.put(15)
q.put(30)
q.put(0)
while not q.empty():
    print(q.get(),end=' ')

output:
0 30 15 20 10


example 3:
import queue
q=queue.PriorityQueue()
q.put(10)
q.put(20)
q.put(15)
q.put(30)
q.put(0)
while not q.empty():
    print(q.get(),end=' ')

output:
0 10 15 20 30



Related links
shallow copy

Deep copy in python language

import copy

l1=[10,20,[30,40],50]
#l2=l1.copy()
#it dnot work for list inside another list
l2=copy.deepcopy(l1)

l2[2][0]=70
print("l2:",l2)
print("l1:",l1)

output:
l2: [10, 20, [70, 40], 50]
l1: [10, 20, [30, 40], 50]



related links:

shallow copy in python

shallow copy in python


l1=[10,20,30,40]
l2=l1
l2[2]=70
print("l2:",l2)
print("l1:",l1)

output:
l2: [10, 20, 70, 40]
l1: [10, 20, 70, 40]

example 2:

l1=[10,20,30,40]
l2=l1.copy()

l2[2]=70
print("l2:",l2)
print("l1:",l1)

output:
l2: [10, 20, 70, 40]
l1: [10, 20, 30, 40]

example 3:

import copy

l1=[10,20,[30,40],50]
#l2=l1.copy()
#it dnot work for list inside another list
l2=copy.copy(l1)

l2[2][0]=70
print("l2:",l2)
print("l1:",l1)

output:
l2: [10, 20, [70, 40], 50]
l1: [10, 20, [70, 40], 50]

python class topic video