First one:
-
how can I create a Thread that doesn’t start right away.If I use
initializewithout a block an exception gets raised. -
how can I subclass Thread, so that I may add some custom attributes, but keep the same functionality as the base Thread class? I’d also like to not have to use the
initialize(&block)method for this.
To better illustrate this:
For the first question:
x = Thread.new
x.run = {
# this should happen inside the thread
}
x.start # i want to manually start the thread
For the second:
x = MyThread.new
x.my_attribute = some_value
x.run = {
# this should happen when the thread runs
}
x.start
I’m looking for something similar to this. Hope you can help.
Question 1
Examining the MRI 1.8.7 source revealed no obvious way to start a thread in the “stopped” state.
What you can do is to have the thread block on a locked mutex, then unlock the mutex when you want the thread to go.
Question 2 (Sort Of)
Did you know you can pass arguments to your thread? Anything passed to Thread.new gets passed through as block arguments:
There are also “thread local variables,” a per-thread key/value store. Use
Thread#[]=to set values, andThread#[]to get them back. You can use string or symbols as keys.Question 2, Really
You can do what you want to do. It’s a lot of work, especially when the usual way of handling threads is so simple. You’ll have to weigh the plusses and minuses: