Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

multithreading - Python threading, threads do not close

I have a Python program and when I exit the application with Ctrl-c, the script does not close. My process still shows in running processes.

#!/usr/bin/env python
import socket
import threading
import Queue
import serial
import mysql.connector
from datetime import datetime, date, time


host = '0.0.0.0'
port = 1024
buffer = 102400
my_queue = Queue.Queue()

class readFromUDPSocket(threading.Thread):

    def __init__(self, my_queue): 
        threading.Thread.__init__(self)
        self.my_queue = my_queue

    def run(self):
        while True:
            buffer1,addr = socketUDP.recvfrom(buffer)
            self.my_queue.put(buffer1)
            print 'UDP received'

class readFromSerial(threading.Thread):

    def __init__(self, my_queue): 
        threading.Thread.__init__(self)
        self.my_queue = my_queue


    def run(self):
        while True:
            buffer2 =  ser.readline(eol=';')
            if buffer2:
                self.my_queue.put(buffer2)
                print 'Serial received'

class process(threading.Thread):

    def __init__(self, my_queue):
        threading.Thread.__init__(self)
        self.my_queue = my_queue
        self.alive = threading.Event()
        self.alive.set()

    def run(self):
        while True: 
            buffer3 = self.my_queue.get()
            today = datetime.now()
            timestamp = today.strftime("%A, %B %d, %Y %H:%M:%S")
            print 'Data pushed at:', timestamp
            print buffer3
            if buffer3.startswith('temp:'):
                temp = buffer3.replace('temp:','')
                cnx = mysql.connector.connect(user='root', password='xxxxx', database='temperature')
                cursor = cnx.cursor()
                cursor.execute("INSERT INTO temperature.temperature (time,temperature) VALUES (%s, %s)", [timestamp, temp])
                print 'Data inserted into Database'
                cnx.commit()
                cursor.close()
                cnx.close()


if __name__ == '__main__':

    # Create socket (IPv4 protocol, datagram (UDP)) and bind to address
    socketUDP = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    socketUDP.bind((host, port))
    ser = serial.Serial('/dev/ttyUSB0', 57600, timeout=2)


    # Instantiate & start threads
    myServer = readFromUDPSocket(my_queue)
    mySerial = readFromSerial(my_queue)
    myDisplay = process(my_queue)

    myServer.start()
    myDisplay.start()
    mySerial.start()

while 1:
    pass

UDPSock.close()
ser.close()

Why does the python thread not close with Ctrl+c?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to make the thread a daemon thread. To do this add the following line after you call the Thread's init

self.setDaemon(True)

A program will exit when only daemon threads are left alive, the main thread is non-daemonic of course


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...