Thread.current

Eric Wong normalperson at yhbt.net
Fri Jan 7 21:57:20 EST 2011


Jimmy Soho <jimmy.soho at gmail.com> wrote:
> Hi All,
> 
> Having an akward noob moment... I have unicorn_rails (1.1.5) running
> with 2 workers, with rails 2.3.10 in development mode. In
> environment.rb at the bottom I have this line of code:
> 
>     puts "#{Time.current} #{Thread.current.object_id}: #{Thread.current.keys.inspect}"

Add the PID ($$), too:

   puts "#{Time.current} #$$ #{Thread.current.object_id}: #{Thread.current.keys.inspect}"

> In a simple controller I have this:
> 
>    def index
>      puts "#{Time.current} #{Thread.current.object_id}: #{Thread.current.keys.inspect}"
>      sleep 5
>      puts "#{Time.current} #{Thread.current.object_id}: #{Thread.current.keys.inspect}"
>      render :text => "foo"
>    end
> 
> In window 1 I tail log/unicorn.log.
> In windows 2 and 3 I start at about the same time:  curl http://localhost:3000
> 
> The output is this:
> 
> 2011-01-08 01:53:56 UTC 2148444460: [:__inspect_key__, :i18n_config,
> :__recursive_key__]
> worker=1 ready
> 2011-01-08 01:53:56 UTC 2148444460: [:__inspect_key__, :i18n_config,
> :__recursive_key__]
> worker=0 ready
> 2011-01-08 01:53:57 UTC 2148444460: [:__inspect_key__, :i18n_config,
> :__recursive_key__]
> 2011-01-08 01:53:59 UTC 2148444460: [:__inspect_key__, :i18n_config,
> :__recursive_key__]
> 2011-01-08 01:54:02 UTC 2148444460: [:__inspect_key__, :i18n_config,
> :__recursive_key__]
> 2011-01-08 01:54:04 UTC 2148444460: [:__inspect_key__, :i18n_config,
> :__recursive_key__]
> 
> Looking at the timings the 2 requests seem to have been handled in
> parallel, as expected.

Yes, that's because you have two worker *processes*

> However, the Thread.current value within those parallel requests is
> always the same.

Just a lucky coincidence :)

> Are two separate requests not handled by different threads? How does
> that work??

Threads (and any other object) object_ids are unique to each process.
They are not unique within all the processes of a machine.

When dealing with native threads under Linux, gettid() is a non-portable
Linux syscall to get the unique identifier of a thread throughout the
entire system.  That's the only way I know of if you want a single
unique identifier (and of course prepending the PID to it).

-- 
Eric Wong


More information about the mongrel-unicorn mailing list