473,766 Members | 2,044 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

embedded python and windows multi threading, can't get it to work

I am trying to run a python programme embedded from C++. I want to run
the same python code concurrently in several threads. I read the manual
on embedding, especially chapter 8, and searched for relevant info on
google all afternoon, but I can't get this to work. What am I doing
wrong? I use python2.4 and vc++7 (.net). The first thread seems to work
okay, the 2nd thread crashes, but the exception information is not very
useful:
(An unhandled exception of type 'System.NullRef erenceException '
occurred in pyembed_test.ex e

Additional information: Object reference not set to an instance of an
object.)

Here is a simplified example, it is heavily based on this article:
http://www.codeproject.com/cpp/embedpython_1.asp

#include <afxwin.h>
#include <Python.h>
#include <Windows.h>
#include <process.h>

#define USE_AFX 0


#if USE_AFX
UINT MyThread(LPVOID lpParam)
#else
void MyThread(void* lpParam)
#endif
{
Py_Initialize() ;
//#if 0
// PyEval_InitThre ads();
PyThreadState *mainthreadstat e = PyThreadState_G et();
PyInterpreterSt ate *maininterprete rstate = mainthreadstate->interp;
PyThreadState *mythreadstate =
PyThreadState_N ew(maininterpre terstate);
PyEval_ReleaseL ock();
PyEval_AcquireL ock();
PyThreadState *tmpstate = PyThreadState_S wap(mythreadsta te);
//#endif
int* num = (int *)lpParam;
int ret = 0;
ret = PyRun_SimpleStr ing("x = []");
ret = PyRun_SimpleStr ing("for i in range(10):\n x.append(i)");
char cmd[100];
sprintf(cmd, "f = open('test%d.tx t', 'w')", *num);
ret = PyRun_SimpleStr ing(cmd);
ret = PyRun_SimpleStr ing("f.write('% s' % x.__str__())");
ret = PyRun_SimpleStr ing("f.close()" );

//#if 0
PyThreadState_S wap(tmpstate);
PyEval_ReleaseL ock();
PyThreadState_C lear(mythreadst ate);
PyThreadState_D elete(mythreads tate);
//#endif

Py_Finalize();
#if USE_AFX
return 0;
#else
_endthread();
#endif
}

class CMyWinApp : public CWinApp
{
public:
CMyWinApp() { }
BOOL InitInstance()
{
int num0 = 0, num1 = 1;
HANDLE hnd0, hnd1;
#if USE_AFX
CWinThread* pThread0 = AfxBeginThread( MyThread, &num0);
hnd0 = pThread0->m_hThread;
CWinThread* pThread1 = AfxBeginThread( MyThread, &num1);
hnd1 = pThread1->m_hThread;
#else
hnd0 = (HANDLE) _beginthread(My Thread, 0, &num0);
hnd1 = (HANDLE) _beginthread(My Thread, 0, &num1);
#endif

// wait for the worker thread to terminate.
WaitForSingleOb ject(hnd0, INFINITE);
WaitForSingleOb ject(hnd1, INFINITE);

return TRUE;
};
};

CMyWinApp app;

Jun 13 '06 #1
1 1707
freesteel wrote:
I am trying to run a python programme embedded from C++. I want to run
the same python code concurrently in several threads. I read the manual
on embedding, especially chapter 8, and searched for relevant info on
google all afternoon, but I can't get this to work. What am I doing
wrong? I use python2.4 and vc++7 (.net). The first thread seems to work
okay, the 2nd thread crashes, but the exception information is not very
useful:
(An unhandled exception of type 'System.NullRef erenceException '
occurred in pyembed_test.ex e


Running one iterpreter in more than one thread is not supported. You
need to create one interpreter per thread using Py_NewInterpret er
(don't forget to read "Bugs and caveats" paragraph). I hope you also
realize the interpreters won't share objects.

Jun 13 '06 #2

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

Similar topics

65
6754
by: Anthony_Barker | last post by:
I have been reading a book about the evolution of the Basic programming language. The author states that Basic - particularly Microsoft's version is full of compromises which crept in along the language's 30+ year evolution. What to you think python largest compromises are? The three that come to my mind are significant whitespace, dynamic typing, and that it is interpreted - not compiled. These three put python under fire and cause...
0
3077
by: Bruce Davis | last post by:
I'm having a problem on windows (both 2000 and XP) with a multi-threaded tkinter gui application. The problem appears to be a deadlock condition when a child thread pops up a Pmw dialog window in the context of a main window. The problem does not occur on HPUX or Linux. The following simple example code illustrates the problem and the work around I've come up with; However, I'd like, very much, to get rid of the kludgy work around....
1
3719
by: amit | last post by:
Hello, I am embedding a python script in a C++ application. The script can be called simultaneously from multiple threads. What is the correct way to implement this situation: 1) Have unique python interpreter instantiations ( Py_Initialize() ) for each thread.
1
2094
by: Carl Waldbieser | last post by:
I have been considering using Python and the Reportlab library for generating PDF reports for the back-end of a web based application. The application runs most of its background tasks on a dedicated server that is Windows based (Win2K or Win2k3). The program that launches the tasks requires a COM-based interface, so I wrote a Python COM server using Mark Hammond's PythonCom libraries and import and run the reporlab modules from there. ...
11
4269
by: Mark Yudkin | last post by:
The documentation is unclear (at least to me) on the permissibility of accessing DB2 (8.1.5) concurrently on and from Windows 2000 / XP / 2003, with separate transactions scope, from separate threads of a multithreaded program using embedded SQL. Since the threads do not need to share transaction scopes, the sqleAttachToCtx family of APIs do not seem to be necessary. <quote> In the default implementation of threaded applications against...
8
2428
by: Brennus | last post by:
I have a dll/so which embeds python. I can verify it works by compiling it as an executable and adding an appropriate main. I tried to write unit tests for this library with ctypes and a simple python script. Access violations and other strange things result. I suspect this is because I am basically embedding python in python at this point. How can I make my dll/so with embedded python support use via ctypes?
21
1262
by: S.Mohideen | last post by:
Hi All, I was thinking about the feasbility of adjusting Python as a compiled language. Being said that I feel these are the following advantages of doing so -- 1) Using the powerful easy-to -use feature of Python programming language constructs. 2) Making the program to run at par with the compiled version of C/C++ program- this is the main benefit which can be derived out of this. 3) Highly re-use existing Python code for High...
0
1984
by: Kurt B. Kaiser | last post by:
Patch / Bug Summary ___________________ Patches : 385 open (+21) / 3790 closed (+21) / 4175 total (+42) Bugs : 1029 open (+43) / 6744 closed (+43) / 7773 total (+86) RFE : 262 open ( +4) / 291 closed ( +4) / 553 total ( +8) New / Reopened Patches ______________________
0
1556
by: Ling | last post by:
I am using boost.python to wrap C++ function which includes directmusic libraries to simply play the midi, but lots of linkage errors "error LNK2001: unresolved external symbol". I wonder if it is possible to work with DirectX - directmusic libs. Are there any ways to wrap it? *********************compilation errors ************************* msvc.link.dll bin\msvc-7.1\debug\threading-multi\playmusic.pyd bin \msvc-7.1\debu...
0
9568
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9404
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10168
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...
0
10008
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7381
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
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3929
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
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
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.