Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Dec 2, 2021. It is now read-only.

Commit d7e37ad

Browse files
committed
updated threading example to use Event object instead of user defined Signal instance
1 parent e4f58fe commit d7e37ad

File tree

2 files changed

+10
-20
lines changed

2 files changed

+10
-20
lines changed

‎18-asyncio/spinner_thread.py‎

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,14 @@
1111
import sys
1212

1313

14-
class Signal: # <1>
15-
go = True
16-
17-
18-
def spin(msg, signal): # <2>
14+
def spin(msg, done): # <2>
1915
write, flush = sys.stdout.write, sys.stdout.flush
2016
for char in itertools.cycle('|/-\\'): # <3>
2117
status = char + ' ' + msg
2218
write(status)
2319
flush()
2420
write('\x08' * len(status)) # <4>
25-
time.sleep(.1)
26-
if not signal.go: # <5>
21+
if done.wait(.1): # <5>
2722
break
2823
write(' ' * len(status) + '\x08' * len(status)) # <6>
2924

@@ -35,13 +30,13 @@ def slow_function(): # <7>
3530

3631

3732
def supervisor(): # <9>
38-
signal = Signal()
33+
done = threading.Event()
3934
spinner = threading.Thread(target=spin,
40-
args=('thinking!', signal))
35+
args=('thinking!', done))
4136
print('spinner object:', spinner) # <10>
4237
spinner.start() # <11>
4338
result = slow_function() # <12>
44-
signal.go=False # <13>
39+
done.set() # <13>
4540
spinner.join() # <14>
4641
return result
4742

‎18b-async-await/spinner_thread.py‎

Lines changed: 5 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,14 @@
1111
import sys
1212

1313

14-
class Signal: # <1>
15-
go = True
16-
17-
18-
def spin(msg, signal): # <2>
14+
def spin(msg, done): # <2>
1915
write, flush = sys.stdout.write, sys.stdout.flush
2016
for char in itertools.cycle('|/-\\'): # <3>
2117
status = char + ' ' + msg
2218
write(status)
2319
flush()
2420
write('\x08' * len(status)) # <4>
25-
time.sleep(.1)
26-
if not signal.go: # <5>
21+
if done.wait(.1): # <5>
2722
break
2823
write(' ' * len(status) + '\x08' * len(status)) # <6>
2924

@@ -35,13 +30,13 @@ def slow_function(): # <7>
3530

3631

3732
def supervisor(): # <9>
38-
signal = Signal()
33+
done = threading.Event()
3934
spinner = threading.Thread(target=spin,
40-
args=('thinking!', signal))
35+
args=('thinking!', done))
4136
print('spinner object:', spinner) # <10>
4237
spinner.start() # <11>
4338
result = slow_function() # <12>
44-
signal.go=False # <13>
39+
done.set() # <13>
4540
spinner.join() # <14>
4641
return result
4742

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /