Reputation: 65
I have code like this. And i need to get names of all threads in test-grp group.
t = threading.Thread(group='test-grp',name='test1',target=testFunc, args = (arg1,arg2))
t.start()
t2 = threading.Thread(group='test-grp',name='test2',target=testFunc, args = (arg1,arg2))
t2.start()
t3 = threading.Thread(group='test-grp',name='test3',target=testFunc, args = (arg1,arg2))
t3.start()
It is possible to do what I want?
Upvotes: 0
Views: 1306
Reputation: 453
This is a sample program for the thread.
import threading
from time import sleep
def find_cube(n):
try:
for i in range(1, n + 1):
sleep(1)
print("Cube of {} is : {}".format(i, i * i * i))
except Exception as e:
print(e)
def find_square(n):
try:
for i in range(1, n + 1):
sleep(1)
print("Square of {} is : {}".format(i, i * i))
except Exception as e:
print(e)
n = int(input("Enter a size of iteration variable for cube and square : "))
th1 = threading.Thread(target= find_cube , name= "CubeThread",args=(n,),group=None,)
th2 =threading.Thread(target= find_square , name= "SqThread",args=(n,),group=None)
th1.start()
sleep(1)
th2.start()
th1.join()
th2.join()
In the above program, you can see that group has None value because like java we do not have ThreadGroup class in python as of now. Thread has a constructor which allows you to set a ThreadGroup in java:
Thread(ThreadGroup group, String name)
We can use this constructor to set our own thread group. Whereas python dose not implemented THreadGroup class yet.
The design of the threading module is loosely based on Java’s threading model. However, where Java makes locks and condition variables basic behavior of every object, they are separate objects in Python. Python’s Thread class supports a subset of the behavior of Java’s Thread class; currently, there are no priorities, no thread groups, and threads cannot be destroyed, stopped, suspended, resumed, or interrupted. The static methods of Java’s Thread class, when implemented, are mapped to module-level functions.
threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)
the group should be None; reserved for future extension when a ThreadGroup class is implemented.
Reference : Python Documentation
Upvotes: 1
Reputation: 17757
From the documentation :
group should be None; reserved for future extension when a ThreadGroup class is implemented.
Code excerpt from threading.Thread :
def __init__(self, group=None, target=None, name=None,
args=(), kwargs=None, *, daemon=None):
assert group is None, "group argument must be None for now"
So right now, you cannot use the group attribute. You should implement that yourself.
Upvotes: 1