Jonathan Livni
Jonathan Livni

Reputation: 107092

introspect current thread in python

How can one instrospect to receive the current thread object?
Consider this somewhat artificial code snippet. The use case is different, but for the sake of simplicity, I've boiled it down the the essential bit

t1 = threading.Thread(target=func)
t2 = threading.Thread(target=func)

marked_thread_for_cancellation = t1

t1.start()
t2.start()

def func():
    if [get_thread_obj] is marked_thread_for_cancellation:   # <== introspect here
        return
    # do something

Upvotes: 0

Views: 904

Answers (2)

Roman Susi
Roman Susi

Reputation: 4199

To make minimal changes to your code, here is probably what you are after:

import threading

def func():
    if threading.current_thread() is marked_thread_for_cancellation:   # <== introspect here
        print 'cancel'
    else:
        print 'otherwise'

t1 = threading.Thread(target=func)
t2 = threading.Thread(target=func)

marked_thread_for_cancellation = t1

t1.start()
t2.start()

But I do not understand what do you mean by introspection. marked_thread_for_cancellation is shared by all threads, all threads have by their own is some local data, accessible via threading.local().

Upvotes: 1

falsetru
falsetru

Reputation: 369074

You can use thread.get_ident function. Compare thread.get_ident() with Thread.ident as follow:

import thread
import threading
import time

marked_thread_for_cancellation = None

def func(identifier):
    while threading.get_ident() != marked_thread_for_cancellation:
        time.sleep(1)
        print('{} is alive'.format(identifier))
    print('{} is dead'.format(identifier))

t1 = threading.Thread(target=func, args=(1,))
t2 = threading.Thread(target=func, args=(2,))
t1.start()
t2.start()
time.sleep(2)
marked_thread_for_cancellation = t1.ident # Stop t1

In Python 3, use threading.get_ident.

You can also use your own identifier instead of thread.get_ident:

import threading
import time

marked_thread_for_cancellation = None

def func(identifier):
    while identifier != marked_thread_for_cancellation:
        time.sleep(1)
        print('{} is alive'.format(identifier))
    print('{} is dead'.format(identifier))

t1 = threading.Thread(target=func, args=(1,))
t2 = threading.Thread(target=func, args=(2,))
t1.start()
t2.start()
time.sleep(2)
marked_thread_for_cancellation = 1 # Stop t1 (`1` is the identifier for t1)

Upvotes: 1

Related Questions