in reply to Perl Threads
but crashes because Tk is not thread safeIf a package is not thread safe, it's just not thread safe, period. The moment you create a second thread all bets are off.
And this would be especially true of something big and complicated like Tk that has its own event loop and probably has other random things going on in the background.
See, when you call create, it creates an entirely new Perl interpreter to run the thread, and every variable you have declared up to that point — including every variable declared in any file that you have loaded up to that point — is duplicated. If Tk is loaded, everything in every package there is going to get duplicated too, and it's not expecting to be. In particular, the C code that's part of the implementation of Tk gets thrown for a loop; and thus, crash.
So, the only way your code in its current form has any chance of working is to make sure all Tk-related stuff is only ever even loaded by one interpreter. Not only do you not do use Tk, you have to ensure that everything that even mentions Tk (including, I suspect, what you have in the "#bunch of stuff that has to happen before the thread starts running") is buried inside a subroutine that starts with require Tk and that subroutine must only be invoked after you've created the last of the various extra threads that you need.
Which means you have no choice but to have the serverRequest thread starting first. Moreover, since that thread will not be able to reference anything in Tk Land directly, whatever UI state it cares about will need to be communicated via shared variables and you'll need event handlers in Tk Land to keep those variables updated. You'll probably also need a semaphore/whatever for the serverRequest thread to wait on until the Tk stuff is ready (and likewise have an event handler in the main thread to trigger it at the appropriate time).
And if this sounds like a mess, that's because it is. It's one thing if you're doing stuff with multiple threads where the other threads have nothing to do with the UI. But if you find yourself needing multiple threads interacting with the UI, then you're probably doing something wrong and will need to take a closer look at Tk to see if there's some other better way of doing it.
|
|---|