- Mastering Concurrency in Python
- Quan Nguyen
- 331字
- 2021-06-10 19:24:03
An example in Python
Let's consider a specific example. In this example, we will be looking at the Chapter03/example4.py file. We will go back to the thread example of counting down from five to one, which we looked at at the beginning of this chapter; take a moment to look back if you do not remember the problem. In this example, we will be tweaking the MyThread class, as follows:
# Chapter03/example4.py
import threading
import time
class MyThread(threading.Thread):
def __init__(self, name, delay):
threading.Thread.__init__(self)
self.name = name
self.delay = delay
def run(self):
print('Starting thread %s.' % self.name)
thread_lock.acquire()
thread_count_down(self.name, self.delay)
thread_lock.release()
print('Finished thread %s.' % self.name)
def thread_count_down(name, delay):
counter = 5
while counter:
time.sleep(delay)
print('Thread %s counting down: %i...' % (name, counter))
counter -= 1
As opposed to the first example of this chapter, in this example, the MyThread class utilizes a lock object (whose variable is named thread_lock) inside of its run() function. Specifically, the lock object is acquired right before the thread_count_down() function is called (that is, when the countdown begins), and the lock object is released right after its ends. Theoretically, this specification will alter the behavior of the threads that we saw in the first example; instead of executing the countdown simultaneously, the program will now execute the threads separately, and the countdowns will take place one after the other.
Finally, we will initialize the thread_lock variable as well as run two separate instances of the MyThread class:
thread_lock = threading.Lock()
thread1 = MyThread('A', 0.5)
thread2 = MyThread('B', 0.5)
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print('Finished.')
The output will be as follows:
> python example4.py
Starting thread A.
Starting thread B.
Thread A counting down: 5...
Thread A counting down: 4...
Thread A counting down: 3...
Thread A counting down: 2...
Thread A counting down: 1...
Finished thread A.
Thread B counting down: 5...
Thread B counting down: 4...
Thread B counting down: 3...
Thread B counting down: 2...
Thread B counting down: 1...
Finished thread B.
Finished.
- iOS面試一戰(zhàn)到底
- Kibana Essentials
- Visual C++程序設計學習筆記
- Python數(shù)據(jù)分析基礎
- Effective C#:改善C#代碼的50個有效方法(原書第3版)
- WSO2 Developer’s Guide
- 數(shù)據(jù)結構(Python語言描述)(第2版)
- Git高手之路
- Learning Neo4j 3.x(Second Edition)
- Full-Stack React Projects
- Interactive Applications Using Matplotlib
- Learning Selenium Testing Tools(Third Edition)
- TradeStation交易應用實踐:量化方法構建贏家策略(原書第2版)
- Kotlin編程實戰(zhàn):創(chuàng)建優(yōu)雅、富于表現(xiàn)力和高性能的JVM與Android應用程序
- C/C++程序員面試指南