0

I am trying to create/open and write to a file from thread.

from threading import Thread


CONNECTION_PORT = 9191

def testl():
    file = open("testfile.txt","w") 
    file.write("Hello World") 
    file.write("This is our new text file") 
    file.write("and this is another line.") 
    file.write("Why? Because we can.") 

    file.close() 

def test():
    t = Thread(target=testl)
    # t.daemon = True
    t.start()


test() 

The problem is that when I un-comment 2nd line (t.daemon = True) of the test function it stops working. Is there any way to make it work in the daemon thread mode ??

I can't find any solution on internet or even related to this. I know it is not the best way for file operation.

  • Possible duplicate of [Python daemon thread does not exit when parent thread exits](https://stackoverflow.com/questions/21843916/python-daemon-thread-does-not-exit-when-parent-thread-exits) – quamrana Sep 13 '17 at 14:54

1 Answers1

0

A daemon thread means that python need not wait for the thread to complete before the program exits. So, what happens is:

  • test() starts the thread

  • test() ends, and the thread containing test() (the main thread probably) ends

  • There are no non-daemon threads

  • python exits.

I don't really think you want the thread to be a daemon thread. If you do, you should have some non-daemon thread call t.join() so that you wait for that thread to complete.

Sam Hartman
  • 6,210
  • 3
  • 23
  • 40