Threads
python3 ( 495357 ) - python3 ( 495357 ) stack: <module>(pydemo:7)
File: py-demo@20241006/pydemo 📋
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys
from abc import ABC, abstractmethod
import threading
lock = threading.Lock()
class SharedResourceWithLock:
def __init__(self):
self.counter = 0
print(f"SharedResourceWithLock __init__ self.counter: {self.counter}")
def increment(self):
with lock:
print(f"Thread {threading.current_thread().name} acquiring lock")
self.counter += 1
print(f"Thread {threading.current_thread().name} released lock, counter = {self.counter}")
def task_with_lock(resource):
for _ in range(3):
resource.increment()
rlock = threading.RLock()
class SharedResourceWithRLock:
def __init__(self):
self.counter = 0
def increment(self):
with rlock:
self.counter += 1
self.double_increment()
def double_increment(self):
with rlock:
self.counter += 1
def task_with_rlock(resource):
resource.increment()
condition = threading.Condition()
class SharedResourceWithCondition:
def __init__(self):
self.ready = False
def produce(self):
with condition:
print("Producing item..."); self.ready = True; condition.notify()
def consume(self):
with condition:
while not self.ready:
condition.wait()
print("Consuming item...")
def task_with_condition():
resource = SharedResourceWithCondition()
producer = threading.Thread(target=resource.produce)
consumer = threading.Thread(target=resource.consume)
consumer.start()
producer.start()
producer.join()
consumer.join()
def func1(msg="hello"):
print("print in func1"); print("hi by print in func1")
if msg != "hello":
return msg
else:
return "hello"
def func2():
print("print in func2"); func1(); func1("say")
def func3():
print("print in func3"); func2()
def func4():
print("print in func4")
func3()
"""Decorator"""
def loop_decorator(func):
def wrapper(*args, **kwargs):
print("Starting the loop...")
func(*args, **kwargs)
print("Loop ended.")
return wrapper
@loop_decorator
def my_while_loop():
count = 0
while count < 5:
print(count)
count += 1
def decorator_one(func):
def wrapper():
print("Decorator One Applied")
func()
return wrapper
def decorator_two(func):
def wrapper():
print("Decorator Two Applied")
func()
return wrapper
@decorator_one
@decorator_two # The order of applying decorators is from the innermost to the outermost, with the decorator closest to the function or class definition being applied first.
def my_function():
print("Hello from my_function!")
def main():
print("print in main")
func4()
my_function()
# Python Syntax and Data Structure Examples
# 1. Basic data types and variables
a = 10 # Integer
b = 3.14 # Float
s = "Hello, World!" # String
lst = [1, 2, 3, 4, 5] # List
tpl = (1, 2, 3) # Tuple
dct = {'name': 'Alice', 'age': 25} # Dictionary
st = {1, 2, 3, 4} # Set
print(f"Integer: {a}, Float: {b}, String: {s}")
# 2. Conditional statements
if a > 5:
print("a is greater than 5")
elif a == 5:
print("a is equal to 5")
else:
print("a is less than 5")
print("ok") if 1 == 1 else print("this will not happen") # value_if_true if condition else value_if_false
http_status = 200
match http_status:
case 200:
print("OK")
case 404:
print("Not Found")
case 500:
print("Internal Server Error")
case _:
print("Unknown Status")
# 3. Loop statement
my_while_loop()
print("List elements:")
for item in lst:
print(item)
for i in range(8):
if i == 4:
continue
if i % 2 == 0:
print(f"{i} is even")
if i == 6:
break
count = 0
while count < 5:
print(count)
count += 1
# 4. Function definition and multiple return values
def calculate(x, y):
add = x + y
sub = x - y
return add, sub # Return multiple values
sum_val, diff_val = calculate(10, 5)
print(f"Sum: {sum_val}, Difference: {diff_val}")
# 5. Lambda expression
square = lambda x: x ** 2
print(f"Square of 4: {square(4)}")
my_lambda = lambda x: (
print(f"Processing value: {x}"), # expression 1
x * 2 # expression 2: return value
)[1]
result = my_lambda(5)
print(result) # prints 10
# 6. List comprehension
squares = [x ** 2 for x in lst]
print(f"List comprehension: {squares}")
# 7. Exception handling
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"Exception caught: {e}")
finally:
print("Exception handling completed")
# Cause an exception to demonstrate automatic stderr capture
try:
1 / 0
except ZeroDivisionError as e:
sys.stderr.write(f"Caught an error: {e}\n")
# 8. File operations
try:
with open("~/wpydemo.example.txt", "w") as f:
f.write("This is a file write example.\n")
except IOError as e:
print(f"File operation error: {e}")
# 9. Class and objects
"""Decorator"""
def add_greeting(cls):
original_method = cls.greet
def new_greet(self):
print("Hello! I am an Animal.")
return original_method(self)
cls.greet = new_greet
return cls
@add_greeting
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
def greet(self):
return "Greetings from Animal!"
class Dog(Animal):
def speak(self):
return f"{self.name} barks"
dog = Dog("Buddy")
print(dog.speak())
print(dog.greet())
class MyClass:
static_variable = "Initial value"
@classmethod
def class_initializer(cls):
print("Static initializer")
cls.static_variable = "Updated value"
def __new__(cls):
print("Creating instance")
return super(MyClass, cls).__new__(cls)
def __init__(self):
print("Initializing instance")
obj = MyClass()
print("obj of MyClass", obj)
class MyAbstractClass(ABC):
@abstractmethod
def my_method(self):
pass
class ConcreteClass(MyAbstractClass):
def my_method(self):
print("Implemented abstract method")
obj = ConcreteClass()
obj.my_method()
AnonymousClass = type('AnonymousClass', (), {'run': lambda self: print("Anonymous class")})
obj = AnonymousClass()
obj.run()
# 10. Decorator function
def logger(func):
def wrapper(*args, **kwargs):
print(f"Calling function: {func.__name__}")
return func(*args, **kwargs)
return wrapper
@logger
def greet(name):
print(f"Hello, {name}")
greet("Alice")
# 11. Stack (using list)
stack = []
stack.append(1)
stack.append(2)
stack.append(3)
print(f"Top of stack: {stack.pop()}")
# 12. Queue (using list)
queue = []
queue.append(1)
queue.append(2)
queue.append(3)
print(f"First element in queue: {queue.pop(0)}")
# 13. Linked List (class implementation)
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, value):
if not self.head:
self.head = Node(value)
else:
current = self.head
while current.next:
current = current.next
current.next = Node(value)
def display(self):
current = self.head
while current:
print(current.value, end=" -> ")
current = current.next
print("None")
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
print("Linked List: ")
ll.display()
# 14. Set operations
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(f"Intersection of sets: {set1 & set2}")
print(f"Union of sets: {set1 | set2}")
# 15. Built-in functions map, filter, reduce
from functools import reduce
lst = [1, 2, 3, 4, 5]
# map function
squared_lst = list(map(lambda x: x ** 2, lst))
print(f"Using map to calculate squares: {squared_lst}")
# filter function
even_lst = list(filter(lambda x: x % 2 == 0, lst))
print(f"Using filter to select even numbers: {even_lst}")
# reduce function
sum_of_lst = reduce(lambda x, y: x + y, lst)
print(f"Using reduce to calculate the sum: {sum_of_lst}")
print("Before pass")
pass # do nothing
print("After pass")
# threading
print("\n--- Lock Example ---")
resource_with_lock = SharedResourceWithLock()
threads = [threading.Thread(target=task_with_lock, args=(resource_with_lock,), name=f'Thread-{i}') for i in range(3)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
print(f"Final counter value (Lock): {resource_with_lock.counter}")
print("\n--- RLock Example ---")
resource_with_rlock = SharedResourceWithRLock()
task_with_rlock(resource_with_rlock)
print(f"Final counter value (RLock): {resource_with_rlock.counter}")
print("\n--- Condition Example ---")
task_with_condition()
if __name__ == "__main__":
main()
Variables All
No. | From | Name | Value |
---|---|---|---|
NA | NA | NA | NA |
Process | Thread Filter | |||||
---|---|---|---|---|---|---|
495357 python3 | 495357 python3 | 495363 python3 | 495362 python3 | 495361 python3 | 495360 python3 | 495359 python3 |
No. | PN | PID | TID | TN | Message |
---|---|---|---|---|---|
1 | python3 | 495357 | 495357 | python3 | print in main |
2 | python3 | 495357 | 495357 | python3 | print in func4 |
3 | python3 | 495357 | 495357 | python3 | print in func3 |
4 | python3 | 495357 | 495357 | python3 | print in func2 |
5 | python3 | 495357 | 495357 | python3 | print in func1 |
6 | python3 | 495357 | 495357 | python3 | hi by print in func1 |
7 | python3 | 495357 | 495357 | python3 | print in func1 |
8 | python3 | 495357 | 495357 | python3 | hi by print in func1 |
9 | python3 | 495357 | 495357 | python3 | Decorator One Applied |
10 | python3 | 495357 | 495357 | python3 | Decorator Two Applied |
11 | python3 | 495357 | 495357 | python3 | Hello from my_function! |
12 | python3 | 495357 | 495357 | python3 | Integer: 10, Float: 3.14, String: Hello, World! |
13 | python3 | 495357 | 495357 | python3 | a is greater than 5 |
14 | python3 | 495357 | 495357 | python3 | ok |
15 | python3 | 495357 | 495357 | python3 | OK |
16 | python3 | 495357 | 495357 | python3 | Starting the loop... |
17 | python3 | 495357 | 495357 | python3 | 0 |
18 | python3 | 495357 | 495357 | python3 | 1 |
19 | python3 | 495357 | 495357 | python3 | 2 |
20 | python3 | 495357 | 495357 | python3 | 3 |
21 | python3 | 495357 | 495357 | python3 | 4 |
22 | python3 | 495357 | 495357 | python3 | Loop ended. |
23 | python3 | 495357 | 495357 | python3 | List elements: |
24 | python3 | 495357 | 495357 | python3 | 1 |
25 | python3 | 495357 | 495357 | python3 | 2 |
26 | python3 | 495357 | 495357 | python3 | 3 |
27 | python3 | 495357 | 495357 | python3 | 4 |
28 | python3 | 495357 | 495357 | python3 | 5 |
29 | python3 | 495357 | 495357 | python3 | 0 is even |
30 | python3 | 495357 | 495357 | python3 | 2 is even |
31 | python3 | 495357 | 495357 | python3 | 6 is even |
32 | python3 | 495357 | 495357 | python3 | 0 |
33 | python3 | 495357 | 495357 | python3 | 1 |
34 | python3 | 495357 | 495357 | python3 | 2 |
35 | python3 | 495357 | 495357 | python3 | 3 |
36 | python3 | 495357 | 495357 | python3 | 4 |
37 | python3 | 495357 | 495357 | python3 | Sum: 15, Difference: 5 |
38 | python3 | 495357 | 495357 | python3 | Square of 4: 16 |
39 | python3 | 495357 | 495357 | python3 | Processing value: 5 |
40 | python3 | 495357 | 495357 | python3 | 10 |
41 | python3 | 495357 | 495357 | python3 | List comprehension: [1, 4, 9, 16, 25] |
42 | python3 | 495357 | 495357 | python3 | Exception caught: division by zero |
43 | python3 | 495357 | 495357 | python3 | Exception handling completed |
44 | python3 | 495357 | 495357 | python3 | Caught an error: division by zero |
45 | python3 | 495357 | 495357 | python3 | File operation error: [Errno 2] No such file or directory: '~/wpydemo.example.txt' |
46 | python3 | 495357 | 495357 | python3 | Buddy barks |
47 | python3 | 495357 | 495357 | python3 | Hello! I am an Animal. |
48 | python3 | 495357 | 495357 | python3 | Greetings from Animal! |
49 | python3 | 495357 | 495357 | python3 | Creating instance |
50 | python3 | 495357 | 495357 | python3 | Initializing instance |
51 | python3 | 495357 | 495357 | python3 | obj of MyClass |
52 | python3 | 495357 | 495357 | python3 | <__main__.main.<locals>.MyClass object at 0x7fa97893f830> |
53 | python3 | 495357 | 495357 | python3 | Implemented abstract method |
54 | python3 | 495357 | 495357 | python3 | Anonymous class |
55 | python3 | 495357 | 495357 | python3 | Calling function: greet |
56 | python3 | 495357 | 495357 | python3 | Hello, Alice |
57 | python3 | 495357 | 495357 | python3 | Top of stack: 3 |
58 | python3 | 495357 | 495357 | python3 | First element in queue: 1 |
59 | python3 | 495357 | 495357 | python3 | Linked List: |
60 | python3 | 495357 | 495357 | python3 | 1 |
61 | python3 | 495357 | 495357 | python3 | -> |
62 | python3 | 495357 | 495357 | python3 | 2 |
63 | python3 | 495357 | 495357 | python3 | -> |
64 | python3 | 495357 | 495357 | python3 | 3 |
65 | python3 | 495357 | 495357 | python3 | -> |
66 | python3 | 495357 | 495357 | python3 | None |
67 | python3 | 495357 | 495357 | python3 | Intersection of sets: {3, 4} |
68 | python3 | 495357 | 495357 | python3 | Union of sets: {1, 2, 3, 4, 5, 6} |
69 | python3 | 495357 | 495357 | python3 | Using map to calculate squares: [1, 4, 9, 16, 25] |
70 | python3 | 495357 | 495357 | python3 | Using filter to select even numbers: [2, 4] |
71 | python3 | 495357 | 495357 | python3 | Using reduce to calculate the sum: 15 |
72 | python3 | 495357 | 495357 | python3 | Before pass |
73 | python3 | 495357 | 495357 | python3 | After pass |
74 | python3 | 495357 | 495357 | python3 | |
75 | python3 | 495357 | 495357 | python3 | --- Lock Example --- |
76 | python3 | 495357 | 495357 | python3 | SharedResourceWithLock __init__ self.counter: 0 |
77 | python3 | 495357 | 495361 | python3 | Thread Thread-2 acquiring lock |
78 | python3 | 495357 | 495361 | python3 | Thread Thread-2 released lock, counter = 1 |
79 | python3 | 495357 | 495359 | python3 | Thread Thread-0 acquiring lock |
80 | python3 | 495357 | 495359 | python3 | Thread Thread-0 released lock, counter = 2 |
81 | python3 | 495357 | 495360 | python3 | Thread Thread-1 acquiring lock |
82 | python3 | 495357 | 495360 | python3 | Thread Thread-1 released lock, counter = 3 |
83 | python3 | 495357 | 495361 | python3 | Thread Thread-2 acquiring lock |
84 | python3 | 495357 | 495361 | python3 | Thread Thread-2 released lock, counter = 4 |
85 | python3 | 495357 | 495359 | python3 | Thread Thread-0 acquiring lock |
86 | python3 | 495357 | 495359 | python3 | Thread Thread-0 released lock, counter = 5 |
87 | python3 | 495357 | 495360 | python3 | Thread Thread-1 acquiring lock |
88 | python3 | 495357 | 495360 | python3 | Thread Thread-1 released lock, counter = 6 |
89 | python3 | 495357 | 495361 | python3 | Thread Thread-2 acquiring lock |
90 | python3 | 495357 | 495361 | python3 | Thread Thread-2 released lock, counter = 7 |
91 | python3 | 495357 | 495359 | python3 | Thread Thread-0 acquiring lock |
92 | python3 | 495357 | 495359 | python3 | Thread Thread-0 released lock, counter = 8 |
93 | python3 | 495357 | 495360 | python3 | Thread Thread-1 acquiring lock |
94 | python3 | 495357 | 495360 | python3 | Thread Thread-1 released lock, counter = 9 |
95 | python3 | 495357 | 495357 | python3 | Final counter value (Lock): 9 |
96 | python3 | 495357 | 495357 | python3 | |
97 | python3 | 495357 | 495357 | python3 | --- RLock Example --- |
98 | python3 | 495357 | 495357 | python3 | Final counter value (RLock): 2 |
99 | python3 | 495357 | 495357 | python3 | |
100 | python3 | 495357 | 495357 | python3 | --- Condition Example --- |
101 | python3 | 495357 | 495363 | python3 | Producing item... |
102 | python3 | 495357 | 495362 | python3 | Consuming item... |
END | 0 | 0 | 0 | 0 | 0 |
×
Commands and Shortcuts
No. | Command | Shortcuts | Description |
---|---|---|---|
1 | GB | Alt + LEFT, Alt + A | Go Backward |
2 | GF | Alt + RIGHT, Alt + D | Go Foreward |
3 | PPE | Alt + UP, Alt + W | Previous Process End |
4 | NPS | Alt + DOWN, Alt + S | Next Process Start |
5 | PB | Ctrl + LEFT, Ctrl + A | current Process Backward |
6 | PF | Ctrl + RIGHT, Ctrl + D | current Process Foreward |
7 | PPTE | Ctrl + UP, Ctrl + W | go to current Process's Previous Thread's End |
8 | PNTS | Ctrl + DOWN, Ctrl + S | go to current Process's Next Thread's Start |
9 | TB | LEFT, A | current Thread Backward |
10 | TF | RIGHT, D | current Thread Foreward |
11 | LU | UP, W | go Line Up of current code block in current thread |
12 | LD | DOWN, S | go Line Down of current code block in current thread |
13 | LP | Shift + UP, Shift + W | go to the occurrence of current line in Previous Loop |
14 | LD | Shift + DOWN, Shift + S | go to the occurrence of current line in Next Loop |
15 | BS | Home | go to code Block Start |
16 | BE | End | go to code Block End |
Project: | py-demo |
Update: | 20241006 |
Commit: | 39c102b2 |
Source Code: | pydemo |
Runtime: | Python3.12 |
System: | MySystemD |
Kernel: | Linux5.10.211 |
Cpu: | Intel:Corei7-7700K |
Machine: | AwesomeMachine |