A thread import problem

B

Bruce Sherwood

I'm trying to do something rather tricky, in which a program imports a
module that starts a thread that exec's a (possibly altered) copy of
the source in the original program, and the module doesn't return.
This has to do with an attempt to run VPython in the Mac Cocoa
context, in which Cocoa is required to be the primary thread, making
it necessary to turn the environment inside out, as currently VPython
invokes the Carbon context as a secondary thread.

I've created a simple test case, displayed below, that illustrates
something I don't understand. The module reads the source of the
program that imported it, comments out the import statement in that
source, and performs an exec of the modified source. The module then
enters an infinite loop, so that there is no return to the original
program; only the exec-ed program runs, and it runs in a secondary
thread.

The puzzle is that if there is any later import statement in the exec
source, the exec program halts on that import statement, with no error
message. I saw a discussion that suggested a need for the statement
"global math" to make the math import work, but that doesn't fix the
problem. I've tried with no success various versions of the exec
statement, with respect to its global and local environment.

Can anyone explain why the math import statement causes a problem?
Thanks for any advice you can give.

Bruce Sherwood

---------------------------
The main program:

from import_test import *
print('exec this file')
global math
from math import sin
print(sin(3.14159/6))

-----------------------------
Contents of import_test:

from threading import Thread
from time import sleep
import sys

prog = open(sys.argv[0]).read()
prog = '#'+prog # comment out the import statement
print(prog)

class worker(Thread):
def run(self):
print('start thread')
exec(prog)

w = worker()
w.start()

while True:
sleep(1)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top