473,569 Members | 2,573 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Need some help with Python/C api and threading

Here is my problem.

I have this library thats hosts another language within python, and
allows that language to call back INTO python.

All is good as long as the other languages calls back on the same
thread. If the callback arrives on a different thread, all hell break
loose and the program dies horribly.

looking at the C api documentation, I came upon the following block of
code :

PyThreadState *tstate;
PyObject *result;

/* interp is your reference to an interpreter object. */
tstate = PyThreadState_N ew(interp);
PyEval_AcquireT hread(tstate);

/* Perform Python actions here. */
result = CallSomeFunctio n();
/* evaluate result */

/* Release the thread. No Python API allowed beyond this point. */
PyEval_ReleaseT hread(tstate);

/* You can either delete the thread state, or save it
until you need it the next time. */
PyThreadState_D elete(tstate);
Which would seem to be what I need. However, I have no idea how to get
at that interp pointer. I tried the following :

PyInterpreterSt ate* interp = PyInterpreterSt ate_New();
PyThreadState *tstate = PyThreadState_N ew(interp);
PyEval_AcquireT hread(tstate);

but then it crashes on the second line ...

Anybody ever done this? As a side note, the hosted language can start an
arbitrary number of threads ...

Steve
Jul 18 '05 #1
7 7971
>>>>> "Steve" == Steve Menard <st**********@v ideotron.ca> writes:

Steve> Here is my problem. I have this library thats hosts
Steve> another language within python, and allows that language to
Steve> call back INTO python.

Steve> All is good as long as the other languages calls back on
Steve> the same thread. If the callback arrives on a different
Steve> thread, all hell break loose and the program dies horribly.

Steve> looking at the C api documentation, I came upon the
Steve> following block of code :

Steve> PyThreadState *tstate; PyObject *result;

Steve> /* interp is your reference to an interpreter
Steve> object. */ tstate = PyThreadState_N ew(interp);
Steve> PyEval_AcquireT hread(tstate);

Steve> /* Perform Python actions here. */ result =
Steve> CallSomeFunctio n(); /* evaluate result */

Steve> /* Release the thread. No Python API allowed beyond
Steve> this point. */ PyEval_ReleaseT hread(tstate);

Steve> /* You can either delete the thread state, or save it
Steve> until you need it the next time. */
Steve> PyThreadState_D elete(tstate);
Steve> Which would seem to be what I need. However, I have no idea
Steve> how to get at that interp pointer. I tried the following :

Steve> PyInterpreterSt ate* interp =
Steve> PyInterpreterSt ate_New(); PyThreadState *tstate =
Steve> PyThreadState_N ew(interp); PyEval_AcquireT hread(tstate);

Steve> but then it crashes on the second line ...

Steve> Anybody ever done this? As a side note, the hosted language
Steve> can start an arbitrary number of threads ...

Steve> Steve

I haven't done this for a while and I'm a little hazy on it, so this
may be incorrect:

I used 'PyThreadState *ts = Py_NewInterpret er();' to set a new
sub-interpreter state if called in a new thread.

If the embedded script calls back into the extension, it restores that
thread state and acquires the GIL before making any other Py* calls by
calling 'PyEval_Restore Thread(ts);'. Before returning, it calls
'PyEval_SaveThr ead()'.
Jul 18 '05 #2
Les Smithson wrote:
>>"Steve" == Steve Menard <st**********@v ideotron.ca> writes:

<SNIP>

I haven't done this for a while and I'm a little hazy on it, so this
may be incorrect:

I used 'PyThreadState *ts = Py_NewInterpret er();' to set a new
sub-interpreter state if called in a new thread.

If the embedded script calls back into the extension, it restores that
thread state and acquires the GIL before making any other Py* calls by
calling 'PyEval_Restore Thread(ts);'. Before returning, it calls
'PyEval_SaveThr ead()'.


Thanks, however I dont think thid will work. The doc for
Py_NewInterpret er says that it created a "an (almost) totally separate
environment for the execution of Python code. In particular, the new
interpreter has separate, independent versions of all imported modules".
This is not good for me, as the callbacks must come in the "main"
interpreter context.

Is there a tutorial somewhere? Or a particularly well written extension
module whose source code I could take a look at?

Let me summarize my situation :

I am writing a python extension, not embedding python. As such, I have
no control over the interpreter, or the threads.

The library I am embedding is not of my own writing. It can create any
number of threads. It can make callbacks into the Python interpreter on
any such thread.

A given thread can original either in python or the library, but control
can go back and forth : A python method can call a library method, which
in turn calls back into python, which calls a linrary method, etc ...
This is a potential problem, because trying to grab in GIL twice from
the same thread will cause a deadlock.
So far, here is what I am doing (without success).

1) In the init_XXX method, I call PyEval_InitThre ads().

2) Every time I pass control to the library, I wrap the call into a
Py_BEGIN_ALLOW_ THREADS/Py_END_ALLOW_TH READS pair. Note that I adde this
recently, and get an error the second time Py_BEGIN_ALLOW_ THREADS is
called, with the following error "Fatal Python error: PyEval_SaveThre ad:
NULL tstate"

3) Finally, whenever I receive a callback from the library, I added
these lines to the start and end of the method :

PyInterpreterSt ate* interp = PyInterpreterSt ate_New();
PyThreadState *tstate = PyThreadState_N ew(interp);
PyEval_AcquireT hread(tstate);

and

PyEval_ReleaseT hread(tstate);
PyThreadState_D elete(tstate);
PyInterpreterSt ate_Delete(inte rp);
Thats about it. I am sure someone, somewhere has done what I need :(
Thanks for any help you can provide,

Steve
Jul 18 '05 #3
Steve Menard wrote:
Les Smithson wrote:
>>> "Steve" == Steve Menard <st**********@v ideotron.ca> writes:

<SNIP>

I haven't done this for a while and I'm a little hazy on it, so this
may be incorrect:

I used 'PyThreadState *ts = Py_NewInterpret er();' to set a new
sub-interpreter state if called in a new thread.

If the embedded script calls back into the extension, it restores that
thread state and acquires the GIL before making any other Py* calls by
calling 'PyEval_Restore Thread(ts);'. Before returning, it calls
'PyEval_SaveThr ead()'.


Thanks, however I dont think thid will work. The doc for
Py_NewInterpret er says that it created a "an (almost) totally separate
environment for the execution of Python code. In particular, the new
interpreter has separate, independent versions of all imported modules".
This is not good for me, as the callbacks must come in the "main"
interpreter context.

Is there a tutorial somewhere? Or a particularly well written extension
module whose source code I could take a look at?

Let me summarize my situation :

I am writing a python extension, not embedding python. As such, I have
no control over the interpreter, or the threads.

The library I am embedding is not of my own writing. It can create any
number of threads. It can make callbacks into the Python interpreter on
any such thread.

A given thread can original either in python or the library, but control
can go back and forth : A python method can call a library method, which
in turn calls back into python, which calls a linrary method, etc ...
This is a potential problem, because trying to grab in GIL twice from
the same thread will cause a deadlock.
So far, here is what I am doing (without success).

1) In the init_XXX method, I call PyEval_InitThre ads().

2) Every time I pass control to the library, I wrap the call into a
Py_BEGIN_ALLOW_ THREADS/Py_END_ALLOW_TH READS pair. Note that I adde this
recently, and get an error the second time Py_BEGIN_ALLOW_ THREADS is
called, with the following error "Fatal Python error: PyEval_SaveThre ad:
NULL tstate"

3) Finally, whenever I receive a callback from the library, I added
these lines to the start and end of the method :

PyInterpreterSt ate* interp = PyInterpreterSt ate_New();
PyThreadState *tstate = PyThreadState_N ew(interp);
PyEval_AcquireT hread(tstate);

and

PyEval_ReleaseT hread(tstate);
PyThreadState_D elete(tstate);
PyInterpreterSt ate_Delete(inte rp);
Thats about it. I am sure someone, somewhere has done what I need :(
Thanks for any help you can provide,

would this:
http://www.python.org/peps/pep-0311.html

...be of any help?

/Simon
Jul 18 '05 #4
Simon Dahlbacka wrote:
Steve Menard wrote:
Les Smithson wrote:
>>>> "Steve" == Steve Menard <st**********@v ideotron.ca> writes:


Thanks for any help you can provide,


would this:
http://www.python.org/peps/pep-0311.html

..be of any help?

/Simon


YES!!!! thats exactly it!!! thanks!

Though I gotta ask, in which version of Python was this introduced?
It'll have a big influence over the compativility list.
Steve
Jul 18 '05 #5
> YES!!!! thats exactly it!!! thanks!

Though I gotta ask, in which version of Python was this introduced?
It'll have a big influence over the compativility list.
Steve


...looking through the cvs logs it seems to me it should be available
from 2.3beta1

(http://cvs.sourceforge.net/viewcvs.p...lude/pystate.h)
Jul 18 '05 #6
If you're using Python 2.3 I'd use the API described in PEP 311:

http://www.python.org/peps/pep-0311.html
Ronald

On 16-jun-04, at 21:30, Steve Menard wrote:
Here is my problem.

I have this library thats hosts another language within python, and
allows that language to call back INTO python.

All is good as long as the other languages calls back on the same
thread. If the callback arrives on a different thread, all hell break
loose and the program dies horribly.

looking at the C api documentation, I came upon the following block of
code :

PyThreadState *tstate;
PyObject *result;

/* interp is your reference to an interpreter object. */
tstate = PyThreadState_N ew(interp);
PyEval_AcquireT hread(tstate);

/* Perform Python actions here. */
result = CallSomeFunctio n();
/* evaluate result */

/* Release the thread. No Python API allowed beyond this point. */
PyEval_ReleaseT hread(tstate);

/* You can either delete the thread state, or save it
until you need it the next time. */
PyThreadState_D elete(tstate);
Which would seem to be what I need. However, I have no idea how to get
at that interp pointer. I tried the following :

PyInterpreterSt ate* interp = PyInterpreterSt ate_New();
PyThreadState *tstate = PyThreadState_N ew(interp);
PyEval_AcquireT hread(tstate);

but then it crashes on the second line ...

Anybody ever done this? As a side note, the hosted language can start
an arbitrary number of threads ...

Steve
--
http://mail.python.org/mailman/listinfo/python-list

--
X|support bv http://www.xsupport.nl/
T: +31 610271479 F: +31 204416173
Jul 18 '05 #7
Steve Menard wrote:
Les Smithson wrote:
>>> "Steve" == Steve Menard <st**********@v ideotron.ca> writes:

<SNIP>

I haven't done this for a while and I'm a little hazy on it, so this
may be incorrect:

I used 'PyThreadState *ts = Py_NewInterpret er();' to set a new
sub-interpreter state if called in a new thread.

If the embedded script calls back into the extension, it restores that
thread state and acquires the GIL before making any other Py* calls by
calling 'PyEval_Restore Thread(ts);'. Before returning, it calls
'PyEval_SaveThr ead()'.


Thanks, however I dont think thid will work. The doc for
Py_NewInterpret er says that it created a "an (almost) totally separate
environment for the execution of Python code. In particular, the new
interpreter has separate, independent versions of all imported modules".
This is not good for me, as the callbacks must come in the "main"
interpreter context.

Is there a tutorial somewhere? Or a particularly well written extension
module whose source code I could take a look at?

Let me summarize my situation :

I am writing a python extension, not embedding python. As such, I have
no control over the interpreter, or the threads.

The library I am embedding is not of my own writing. It can create any
number of threads. It can make callbacks into the Python interpreter on
any such thread.

A given thread can original either in python or the library, but control
can go back and forth : A python method can call a library method, which
in turn calls back into python, which calls a linrary method, etc ...
This is a potential problem, because trying to grab in GIL twice from
the same thread will cause a deadlock.
So far, here is what I am doing (without success).

1) In the init_XXX method, I call PyEval_InitThre ads().

2) Every time I pass control to the library, I wrap the call into a
Py_BEGIN_ALLOW_ THREADS/Py_END_ALLOW_TH READS pair. Note that I adde this
recently, and get an error the second time Py_BEGIN_ALLOW_ THREADS is
called, with the following error "Fatal Python error: PyEval_SaveThre ad:
NULL tstate"

3) Finally, whenever I receive a callback from the library, I added
these lines to the start and end of the method :

PyInterpreterSt ate* interp = PyInterpreterSt ate_New();
PyThreadState *tstate = PyThreadState_N ew(interp);
PyEval_AcquireT hread(tstate);

and

PyEval_ReleaseT hread(tstate);
PyThreadState_D elete(tstate);
PyInterpreterSt ate_Delete(inte rp);
Thats about it. I am sure someone, somewhere has done what I need :(


In the code for the Sybase extension module I ended up with some code to
manage the GIL and a lock per database context and database connection.

http://www.object-craft.com.au/proje.../download.html

The code is a little complicated in that you can disable all locking
support at compile time if it is not important to you.

- Dave

--
http://www.object-craft.com.au
Jul 18 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
4488
by: Wenning Qiu | last post by:
I am researching issues related to emdedding Python in C++ for a project. My project will be running on an SMP box and requires scalability. However, my test shows that Python threading has very poor performance in terms of scaling. In fact it doesn't scale at all. I wrote a simple test program to complete given number of iterations of...
4
1149
by: Philip Smith | last post by:
Hi I am fairly new to Python threading and my needs are simple(!) I want to establish a number of threads each of which work on the same computationally intensive problem in different ways. I am using the thread module rather than the threading module. My problem is I can't see how (when one thread completes) to ensure that the
8
1641
by: Nathan Pinno | last post by:
Hi all, I need help figuring out how to fix my code. I'm using Python 2.2.3, and it keeps telling me invalid syntax in the if name == "Nathan" line. Here is the code if you need it. #This program asks for a password, then asks for the user's name after the correct password has been supplied. The computers response will vary, # depending...
3
1363
by: trialproduct2004 | last post by:
Hi all I am having problem at a time of handling threading. I am having application containing thread. In thread procedure i ma using recursive function. This recursive function is adding some entries in my temprary file. But when i called abort on thread it is not aborting that thread. After calling aborting still entries are getting...
4
2570
by: yaffa | last post by:
dear folks, i'm trying to append a semicolon to my addr string and am using the syntax below. for some reason the added on of the ; doesn't work. when i print it out later on it only shows the original value of addr. addr = incident.findNextSibling('td') addr.append('%s;') thanks
6
1338
by: Benjamin Walling | last post by:
We have 109 remote offices all running Sybase ASA Server. We collect data from these offices and consolidate it into our main server. I have written a program that will read from each office and synchronize the data. It takes a while to run because each office only has a 128k Frame Relay. I have two database classes: one for accessing the...
5
3093
by: Sinan Nalkaya | last post by:
hello, i need a function like that, wait 5 seconds: (during wait) do the function but function waits for keyboard input so if you dont enter any it waits forever. i tried time.sleep() but when i used time.sleep in while, the function in while never executed. then i found something about Timer but couldnt realize any algorithm in my mind.
1
1255
by: daniel | last post by:
can someone give me a good threading tutorial thx
5
2025
by: bean330 | last post by:
Hey, I'm somewhat new to C# and I need a little help, please! I'm selecting a bunch of records, setting properties on a COM executable and then calling a method on that executable to run. I want to run the executable in separate threads because they can be long-running and it would be optimal for us to run a bunch simultaneously. I've...
22
4012
by: Chuck Connors | last post by:
Hey guys. I'm working on a little program to help my wife catalog her/ our coupons. I found a good resource but need help formatting the text data so that I can import it into a mysql database. Here's the data format: 409220000003 Life Fitness Products $1 (12-13-08) (CVS) 546500181141 Oust Air Sanitizer, any B1G1F up to $3.49 (1-17-09)...
0
7701
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7615
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7979
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5514
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5219
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3643
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2115
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1223
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
940
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.