Dec-14-2018, 12:21 AM
Great thank you!
I have been reading up threading and the way I understand it, it is basically expanding your code from vertical to horizontal (running it in parallel). So if you had 5 workers, instead of each waiting for the one before it to be done before it can do its task, they can all do them at the same time. Here is a script from a video I watched:
Can I have workers perform different tasks?
Here's what I have tried:
I have been reading up threading and the way I understand it, it is basically expanding your code from vertical to horizontal (running it in parallel). So if you had 5 workers, instead of each waiting for the one before it to be done before it can do its task, they can all do them at the same time. Here is a script from a video I watched:
import threading import time def talker(n, name): print('{} is sleeping\n'.format(name)) time.sleep(n) print('{} has woken up!\n'.format(name)) start = time.time() threads_list = [] for k in range(5): t = threading.Thread(target=talker, name='thread{}'.format(k),args=(5, 'thread{}'.format(k))) threads_list.append(t) t.start() for t in threads_list: t.join() end = time.time() print('time taken: {}'.format(end-start))With out threading this task would take 25 seconds. With threading, each worker does the same job at the same time. So the code only runs for 5 seconds:
Output:thread0 is sleeping
thread1 is sleeping
thread2 is sleeping
thread3 is sleeping
thread4 is sleeping
thread0 has woken up!
thread2 has woken up!
thread3 has woken up!
thread4 has woken up!
thread1 has woken up!
time taken: 5.001632213592529
But how does this work with ser.readline Larz60+. How do I define a function to read the line and write it to a file?Can I have workers perform different tasks?
Here's what I have tried:
import threading import time import datetime import serial ser = serial.Serial() ser.port = 'COM2' ser.baudrate = 460800 ser.timeout = 0.02 ser.bytesize = 8 ser.stopbits = 1 ser.open() f = open('thread.txt', 'w') def reader(): line = ser.readline() time = datetime.datetime.now() f.write(str(time) + ' ' + str(line.replace(b'\r\n', b'').decode('utf-8')) + '\n') while 1: start = time.time() threads_list = [] for k in range(5): t = threading.Thread(target=reader) threads_list.append(t) t.start() for t in threads_list: t.join() end = time.time() print('time taken: {}'.format(end-start)) ser.close()and the result:
Output:2018-12-13 17:11:43.397547
2018-12-13 17:11:43.397547
2018-12-13 17:11:43.397547
2018-12-13 17:11:43.397547
2018-12-13 17:11:43.397547
2018-12-13 17:11:43.418060
2018-12-13 17:11:43.418060
2018-12-13 17:11:43.418060
2018-12-13 17:11:43.418060
2018-12-13 17:11:43.418060
2018-12-13 17:11:43.438575
2018-12-13 17:11:43.438575
2018-12-13 17:11:43.438575
2018-12-13 17:11:43.438575
...
It's not even reading the line from the port.