On 17/07/2019 09.58, Barry Scott wrote:
>
>> On 16 Jul 2019, at 20:48, Dan Stromberg <[email protected]> wrote:
>>
>>
>>
>> A question arises though: Does threading.active_count() only show Python
>> threads created with the threading module? What about threads created with
>> the thread module?
> Only pythons threads, if you think about it why would python care about
> threads it does not control?
As the docs say, this counts threading.Thread objects. It does not count
all threads started from Python: threads started with the _thread
module, for instance, are not included.
What is more, threads started in external libraries can acquire the GIL
and run Python code. A great example of this are QThreads in a PyQt5
application: QThreads are started by the Qt runtime, which calls a Qt
slot. This Qt slot then might happen to be implemented in Python. I'm
sure other libraries do similar things.
Example with _thread just to check active_count behaviour:
#!/usr/bin/env python3
import threading
import _thread
import time
def thread_func(i):
print('Starting thread', i)
time.sleep(0.5)
print('Thread done', i)
print('Using threading.Thread')
t1 = threading.Thread(target=thread_func, args=(1,))
t1.start()
time.sleep(0.1)
print('active threads:', threading.active_count())
t1.join()
print('Using threading & _thread')
t1 = threading.Thread(target=thread_func, args=(1,))
t1.start()
t2_id = _thread.start_new_thread(thread_func, (2,))
time.sleep(0.1)
print('active threads:', threading.active_count())
time.sleep(0.6)
print('Done, hopefully')
--
https://mail.python.org/mailman/listinfo/python-list