What is a python thread

后端 未结 4 1169
执笔经年
执笔经年 2020-12-12 19:09

I have several questions regarding Python threads.

  1. Is a Python thread a Python or OS implementation?
  2. When I use htop a multi-threaded script has multi
4条回答
  •  执念已碎
    2020-12-12 19:50

    I'm not familiar with the implementation, so let's make an experiment:

    import threading
    import time
    
    def target():
        while True:
            print 'Thread working...'
            time.sleep(5)
    
    NUM_THREADS = 5
    
    for i in range(NUM_THREADS):
        thread = threading.Thread(target=target)
        thread.start()
    
    1. The number of threads reported using ps -o cmd,nlwp is NUM_THREADS+1 (one more for the main thread), so as long as the OS tools detect the number of threads, they should be OS threads. I tried both with cpython and jython and, despite in jython there are some other threads running, for each extra thread that I add, ps increments the thread count by one.

    2. I'm not sure about htop behaviour, but ps seems to be consistent.

    3. I added the following line before starting the threads:

      thread.daemon = True
      

      When I executed the using cpython, the program terminated almost immediately and no process was found using ps, so my guess is that the program terminated together with the threads. In jython the program worked the same way (it didn't terminate), so maybe there are some other threads from the jvm that prevent the program from terminating or daemon threads aren't supported.

    Note: I used Ubuntu 11.10 with python 2.7.2+ and jython 2.2.1 on java1.6.0_23

提交回复
热议问题