in reply to Callback from threaded shared library
Basically, you cannot call perl code across threads. If you create an interpreter in the context of your main thread, call into it and retrieve a code reference, either directly, or indirectly in the form of method addresses attached to a returned object, attempting to call that/those address from a separate thread is going to crash.
To allow multiple perl threads to run, a separate interpreter is started in each thread, and all the context they require to run is stored in thread-local storage. If you pass a callback generated in one interpreter (thread) across thread boundaries within your C code and then attempt to call it, the thread relative context will be missing and a crash is inevitable.
Even if you started a second interpreter in the second thread, a callback created from within the first thread/interpreter will not work if passed to the second interpreter.
The best option would be to start your interpreter in it's own thread and have the perl code in that thread go into an endless loop blocking on a read from a queue.
Whenever your other (C) threads need something done by the perl thread, the post a token onto the queue that tells the perl code what is required. The C thread then blocks reading the queue until the perl code push the required results back onto the queue. You'll need to have the request tokens passed in carry an identifier (threadid) of the "calling thread" so that it can attach the same identifier to the results it posts for that thread. The C code reading the queue will need to discriminate between replies intended for it, and those intended for other calling threads, and leave any not intended for it on the queue and contniue blocking.
This is the message loop model used by gui's like tk and others.
|
|---|