Skip to content

Commit b578688

Browse files
authored
Made virtual_can_demo.py thread safe
1 parent 66ce4aa commit b578688

1 file changed

Lines changed: 12 additions & 14 deletions

File tree

examples/virtual_can_demo.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,25 @@
55
This demo creates multiple processes of Producers to spam a socketcan bus.
66
"""
77

8-
import time
9-
import logging
10-
import concurrent.futures
8+
from time import sleep
9+
from concurrent.futures import ProcessPoolExecutor
1110

1211
import can
1312

1413

1514
def producer(id):
16-
""":param id: Spam the bus with messages including the data id."""
15+
"""Spam the bus with messages including the data id.
16+
:param int id: the id of the thread/process
17+
"""
1718

18-
bus = can.interface.Bus(bustype='socketcan', channel='vcan0')
19-
for i in range(16):
20-
msg = can.Message(arbitration_id=0x0cf02200+id, data=[id, i, 0, 1, 3, 1, 4, 1])
21-
bus.send(msg)
22-
23-
# TODO Issue #3: Need to keep running to ensure the writing threads stay alive. ?
24-
time.sleep(2)
19+
with can.ThreadSafeBus(bustype='socketcan', channel='vcan0') as bus:
20+
for i in range(16):
21+
msg = can.Message(arbitration_id=0x0cf02200+id, data=[id, i, 0, 1, 3, 1, 4, 1])
22+
bus.send(msg)
23+
sleep(1.0)
2524

2625
if __name__ == "__main__":
27-
#logging.getLogger('').setLevel(logging.DEBUG)
28-
with concurrent.futures.ProcessPoolExecutor(max_workers=4) as executor:
26+
with ProcessPoolExecutor(max_workers=4) as executor:
2927
executor.map(producer, range(5))
3028

31-
time.sleep(2)
29+
sleep(1.0)

0 commit comments

Comments
 (0)