473,800 Members | 2,282 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Bus error in PyGILState_Rele ase (callbacks from other threads)

[Note: I don't check the mailbox in the header. Please send any
correspondence to the address listed below.]

I'm trying to write an extension in C that delivers callbacks to
Python. The C code starts several threads, and I'd like one of the new
threads that is started to be able to deliver callbacks to Python. I
thought I could do this by wrapping the callback function in
PyGILState_Ensu re / PyGILState_Rele ase. When I do this, the Python code
in the callback in between those two calls certainly works, but when
PyGILState_Rele ase is called, the process dies with a bus error!

Is this supposed to work, or am I doing something terribly wrong? (Code
attached below.) This is the official Python 2.4.3 build for OS X; I'm
running OS X 10.4.6.

My examination of the source suggests that head_mutex in pystate.c is
becoming 0x20, which is not so good, since it is supposed to be a
pointer. (in pystate.c: PyGILState_Rele ase calls
PyThreadState_D eleteCurrent, which calls tstate_delete_c ommon, which
calls HEAD_UNLOCK, which calls PyThread_releas e_lock in
thread_pthread. h; this function's first action is to call
pthread_mutex_l ock, which dies on a bus error because the value of
head_mutex that HEAD_UNLOCK got and passed to PyThread_releas e_lock
pointed off into outer space. This is educated guesswork -- gdb's not
reporting a whole lot in the call stack.) Interestingly, the prior call
to HEAD_LOCK in tstate_delete_c ommon succeeds, so it sort of looks like
memory is being corrupted in between the HEAD_LOCK at around
pystate.c:245 and the HEAD_UNLOCK around pystate.c:254.

HEAD_LOCK(); // <-- guess: this is succeeding
for (p = &interp->tstate_head; ; p = &(*p)->next) {
if (*p == NULL)
Py_FatalError(
"PyThreadState_ Delete: invalid tstate");
if (*p == tstate)
break;
}
*p = tstate->next;
HEAD_UNLOCK(); // <-- guess: this is resulting in a bus error

Here's some Pyrex code that crashes 100% of the time for me:

--- snip (foo.pyx) ---
cdef extern from "stdio.h":
int printf(char *str, ...)

cdef extern from "Python.h":
ctypedef int PyGILState_STAT E
PyGILState_STAT E PyGILState_Ensu re()
void PyGILState_Rele ase(PyGILState_ STATE gstate)

cdef extern from "pthread.h" :
ctypedef void *pthread_t # it'll do
int pthread_create( pthread_t *thread, void *attr,
void *(*start_routin e)(void *), void *arg)

cdef extern void *func(void *x):
printf("Enterin g func(%p)\n", x)

cdef PyGILState_STAT E st
printf("PyGILSt ate_Ensure\n")
st = PyGILState_Ensu re()
printf("PyGILSt ate_Release\n")
PyGILState_Rele ase(st)
printf("Leaving func\n")

def callFuncDirectl y():
func(NULL)

def callFuncInThrea d():
cdef pthread_t thr
pthread_create( &thr, NULL, func, NULL);

--- snip (setup.py) ---

from distutils.core import setup
from distutils.exten sion import Extension
from Pyrex.Distutils import build_ext

setup(
name = 'foo',
ext_modules = [Extension("foo" , ["foo.pyx"])],
cmdclass = {'build_ext': build_ext},
)

--- end ---

I ran 'python setup.py build_ext --inplace', then started python in
that directory, did 'import foo', and then 'foo.callFuncDi rectly()'. No
crash. Then I called 'foo.callFuncIn Thread()'. Prints
'PyGILState_Rel ease' and then falls over.

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_PROTECTION _FAILURE at address: 0x00000020
[Switching to process 25649 thread 0x313]
0x900017dc in pthread_mutex_l ock ()
(gdb) bt
#0 0x900017dc in pthread_mutex_l ock ()
#1 0x002be654 in PyThread_releas e_lock (lock=0x20) at
/Volumes/Data/Users/ronald/Universal/python24-fat/Python/thread_pthread. h:439
#2 0x00045600 in func (__pyx_v_x=0x0) at foo.c:72
#3 0x9002ba68 in _pthread_body ()

Any help (or even just confirmation along the lines of "this is
supposed to work, file a bug") would be greatly appreciated.

thanks,
Geoff Schmidt
gschmidt [[a t]] gschmidt [[d o t]] org (send correspondence here, not
the address in the header)

Jun 20 '06 #1
1 2204
ge**********@gm ail.com wrote:
I'm trying to write an extension in C that delivers callbacks to
Python. The C code starts several threads, and I'd like one of the new
threads that is started to be able to deliver callbacks to Python. I
thought I could do this by wrapping the callback function in
PyGILState_Ensu re / PyGILState_Rele ase. When I do this, the Python code
in the callback in between those two calls certainly works, but when
PyGILState_Rele ase is called, the process dies with a bus error!


The fine folks on the Pyrex list figured out the problem:
PyEval_InitThre ads() needs to be called somewhere before any of the
threading calls are made. For a fixed version of my test program,
please see the Pyrex list archives.

thanks,
Geoff Schmidt
gschmidt [[a t]] gschmidt [[d o t]] org (send correspondence here, not
the address in the header)

Jun 20 '06 #2

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

Similar topics

4
2740
by: Randall Hopper | last post by:
What is the correct way to propagate exceptions from Python callbacks? When I do this: Python -> C++ -> Python Callback (example attached) an exception raised in the callback doesn't make it back across C++ to Python. It appears that PyGILState_Release() at the bottom of the callback
10
7476
by: Alfonso Morra | last post by:
This may be considered as OT since the C++ Standard says not one word about threads. Nevertheless, C++ is routinely and widely used to write solid multithreaded code. I wondered if anyone has any pointers/references to invoking callbacks accross different threads? (google is not showing much promise, and I'm running out of both time and patience...)
5
2249
by: Adam Clauss | last post by:
Couple questions: 1) I have an application using TCP sockets. When I make a call to BeginReceive(), is the callback I specify called in the current thread or from a new thread? 2) Similar to the first, with regards to events. When I actually call an event (with some number of delegates added to it), is each thread called sequentially in the calling thread, or is each executed asynchronously in its own?
2
2386
by: Ann Huxtable | last post by:
Hi, I want to do two types of async callbacks in C#. One involves spawning a worker thread, and the other does not invlve threads: Case 1 (Span new thread) ---------------------------- class Fred { private MyParams params = null ;
1
2103
by: Kirill Simonov | last post by:
Hi, Could someone tell me why my extension module works under Python 2.4, but fails with Segmentation Fault under Python 2.3? Here is the stripped version: ================================================ #include <Python.h> static PyObject * test_gil(PyObject *self)
4
2233
by: emma_middlebrook | last post by:
Hi Advice needed about what's the best in the following situation. In essence, I have a GUI that needs to detail time taken to do jobs that execute in their own thread. Currently, the GUI thread instantiates a class that wraps a job, handing it a callback (delegate) to call once the job has finished. On callback, always on a different thread than the GUI thread,
1
1898
by: brekehan | last post by:
I am going to try and keep this non-OS specific, especially when I am trying to implement this on multiple OSes The need has arisen for a callback mechanism. Currently, things are going to go something like this: 1) Application requests some work to be done from API and supplies a memory buffer that cannot be modified until called back 2) API does work, fills buffer, and calls back Application when completed <--I am working on this...
0
2044
by: choukse | last post by:
Hi All, I am trying to bind to ADAM instance with a windows user through JNDI and it keeps failing. My ADAM and AD is running on same Windows 2k3 server. But, through LDP I am able to bind with the same windows user successfully and browse through the entire tree successfully. The error is as below
0
1171
by: mathieu | last post by:
Hello and happy new year folks, I am experiencing a seg fault while using the python interface to the VTK library (debian oldstable, python 2.3). The VTK library is wrapped by a custom mechanism to provide a python API. In particular they implemented a way so that a python function can be called in response to an event(*). Basically all the code is doing is: { PyGILState_STATE state = PyGILState_Ensure();
0
10505
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10253
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9090
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7580
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6813
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5471
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5606
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3764
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2945
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.