Cómo hacer referencia al hilo actual

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?

preguntado el 01 de febrero de 12 a las 22:02

weird im finding self doesnt refer to the thread: Thread.new{ p self }.join huellas dactilares main -

3 Respuestas

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.

yo usaría 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 significa.

Respondido 02 Feb 12, 02:02

La respuesta corta es: Thread.current is most common approach to get current thread

Respondido el 23 de junio de 17 a las 19:06

In addition to Alex's answer, I noticed that t = Thread.new{p t} should be avoided. In some cases, when running the sub-thread is fast, the assignment to the variable t in the main thread might not be done by the time of its call inside the sub-thread, in which case, t is not defined (returning nil) or is something else.

Respondido 23 Feb 12, 03:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.