1

I want to create an endless thread with python3.7 that receives an input signal in the background. It should stop when my program, so main stops. I set my thread to daemon=True but it just continues running. I also checked the Daemon-state afterwards and it was True.

The same problem occurs when I regularily check in my thread if the main thread is still active and try to stop it when not. The main_thread will always be seen as active.

Here is my code with both possibilities. The input in main is just that I can stop the main routine when I want to.

import threading
import serial as s

port = "/dev/ttyS0"   #Pi 2
rounds_receiving = 24   
ser = s.Serial(port, baudrate = 230400) #default:  parity = s.PARITY_NONE, stopbits = s.STOPBITS_ONE, bytesize = s.EIGHTBITS
received_data_original = []

def receive_data(length_receiving_max):
    for i in range(3):
        global received_data_original
    
        received_data_original = ser.read(length_receiving_max)
        
        for i  in range(length_receiving_max):
            print('%d: %s'%(i, received_data_original[i]))

        if(threading.main_thread().is_alive()):
            print('main is alive')
        else:
            x.join()
            print('main killed')
        

if __name__ == "__main__":
    x = threading.Thread(target=receive_data, args=(rounds_receiving, ), daemon = True)
    if(threading.main_thread().is_alive()):
        print('main alive')
    x.start()
    inp = input()

This is the output after I stopped the main by writing a '0' and enter to input:

...
21: 0
22: 136
23: 191
main is alive

0
0: 255
1: 0
2: 2
3: 244
4: 88
5: 156
6: 55
7: 4
8: 0
9: 0
10: 0
11: 0
12: 0
13: 0
14: 0
15: 0
16: 0
17: 0
18: 0
19: 0
20: 0
21: 0
22: 136
23: 191
main is alive

Does anyone has an Idea, why it does not work and how to fix my problem?

curiesse
  • 11
  • 2

0 Answers0