in reply to OO and Threads conflict?

I am betting that every thread created in this example already shares a variable with the main thread - the object itself!

$self->{thread} = threads->new(\&reader, $self);      # Start thread

Therefore any functionality of the object should be available to the thread.

I think the concept of wrapping threads in objects is a little confusing and dangerous. A thread proc is different than a object function - it represents a new path of execution.

It may be cool to wrap a thread in an object but objects go out scope - $self will become invalid if the object goes out scope before thread function reader exits.

Replies are listed 'Best First'.
Re^2: OO and Threads conflict?
by Aristotle (Chancellor) on Sep 21, 2002 at 22:40 UTC
    $self will become invalid if the object goes out scope before thread function reader exits.
    (Disclaimer: I'm not sure I'm following what you're saying.) That said, this ain't C++ so $self is a reference, not a pointer, and unlike pointers, references are smart. If the variable goes out of scope in one place but is also referenced from another scope, it won't become "invalid". (What's that, anyway? Do you mean undef? Dangling pointer (no such thing in Perl)? Or something else?) You might want to look into closures.

    Makeshifts last the longest.

      Thanks Aristotle I will look into closures.

      I usually test my assumptions but I'm stuck working today.

      I have spent too many years chasing down pointer problems in C/C++ - this is for sure, point taken.
      I am making a dangerous assumption that the function reader is equivalent to a thread proc in C/C++. If so, it is basically just like the main() function in C. It will need to return before dying. If I pass an object into a thread proc that some how controls the life-time of the thread, I hope that the object's life-time exceeds that of the thread.
      If the object ceases to exist before the thread terminates - how will I control the thread.

      Threads can cause wickedly interesting problems!!!

        Threads can cause wickedly interesting problems!!!

        Stupid question. If threads cause such hard to track down problems, then shouldn't you not use them unless they really give you enough to be worth that hassle? Which seems to me to be almost never?