Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to refer to the current thread

When I want to refer to the current thread within the environment of a thread, several strategies seem to work:

  • t = Thread.new{p t}
  • Thread.new{|t| p t}
  • Thread.new{p Thread.current}
  • Thread.new{p self}

Are they all equivalent? Is there a reason to choose one over the others in a specific context?

like image 989
sawa Avatar asked Feb 01 '12 22:02

sawa


People also ask

How do I get the current running thread?

In the run() method, we use the currentThread(). getName() method to get the name of the current thread that has invoked the run() method. We use the currentThread(). getId() method to get the id of the current thread that has invoked the run() method.

How do you name a thread?

Naming Thread By we can change the name of the thread by using the setName() method. The syntax of setName() and getName() methods are given below: public String getName(): is used to return the name of a thread. public void setName(String name): is used to change the name of a thread.

What is the use of current thread?

The currentThread() method of thread class is used to return a reference to the currently executing thread object.

What is current thread in C#?

A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as CurrentThread to check the current running thread. Or in other words, the value of this property indicates the current running thread.


2 Answers

self will only work if you call it directly within the block passed to Thread.new, not if you call it from inside a method on another class which runs on that thread. If you use the Thread.new { |t| p t} approach, you will have to pass t around if you want to use it inside other methods which are run on that thread. But Thread.current works no matter where you call it from.

I would use Thread.current, because it makes it obvious what you're doing to anybody reading the code. Some readers might not know that if the Thread.new block takes a parameter, the new thread will be passed in to that parameter. self might not be 100% clear either. But any reader should immediately be able to understand what Thread.current means.

like image 63
Alex D Avatar answered Oct 10 '22 11:10

Alex D


The short answer is: Thread.current is most common approach to get current thread

like image 41
Daniel Garmoshka Avatar answered Oct 10 '22 10:10

Daniel Garmoshka