PyObject * py_guestfs_close (PyObject *self, PyObject *args) { PyThreadState *py_save = NULL; PyObject *py_g; guestfs_h *g; size_t i, len; PyObject **callbacks; if (!PyArg_ParseTuple (args, (char *) "O:guestfs_close", &py_g)) return NULL; g = get_handle (py_g); /* As in the OCaml bindings, there is a hard to solve case where the * caller can delete a callback from within the callback, resulting * in a double-free here. XXX */ callbacks = get_all_event_callbacks (g, &len); if (PyEval_ThreadsInitialized ()) py_save = PyEval_SaveThread (); guestfs_close (g); if (PyEval_ThreadsInitialized ()) PyEval_RestoreThread (py_save); for (i = 0; i < len; ++i) Py_XDECREF (callbacks[i]); free (callbacks); Py_INCREF (Py_None); return Py_None; }
void init() { if (etiss::cfg().get<bool>("pyinitialize",true)) { Py_Initialize(); if (etiss::cfg().get<bool>("pyinittheads",true)) { if (PyEval_ThreadsInitialized()==0) { PyEval_InitThreads(); // init gil PyEval_ReleaseLock(); // release gil etiss::log(etiss::VERBOSE,"PyEval_InitThreads() called."); } } etiss::log(etiss::VERBOSE,"Py_Initialize() called."); } run([]() { PyEval_AcquireLock(); // lock gil if (etiss::verbosity() >= etiss::INFO) PyRun_SimpleString("print('ETISS: INFO: ETISS has been build with python support.')\n"); //Py_InitModule3("etiss", ETISSMethods,"ETISS python bindings"); PyEval_ReleaseLock(); // release gil }); }
PyMODINIT_FUNC initlibevwrapper(void) { PyObject *m; if (PyType_Ready(&libevwrapper_LoopType) < 0) return; libevwrapper_IOType.tp_new = PyType_GenericNew; if (PyType_Ready(&libevwrapper_IOType) < 0) return; libevwrapper_AsyncType.tp_new = PyType_GenericNew; if (PyType_Ready(&libevwrapper_AsyncType) < 0) return; m = Py_InitModule3("libevwrapper", module_methods, "libev wrapper methods"); PyModule_AddIntConstant(m, "EV_READ", EV_READ); PyModule_AddIntConstant(m, "EV_WRITE", EV_WRITE); Py_INCREF(&libevwrapper_LoopType); PyModule_AddObject(m, "Loop", (PyObject *)&libevwrapper_LoopType); Py_INCREF(&libevwrapper_IOType); PyModule_AddObject(m, "IO", (PyObject *)&libevwrapper_IOType); Py_INCREF(&libevwrapper_AsyncType); PyModule_AddObject(m, "Async", (PyObject *)&libevwrapper_AsyncType); if (!PyEval_ThreadsInitialized()) { PyEval_InitThreads(); } }
void redo() { if (!done_ && PyEval_ThreadsInitialized()) { state_ = PyGILState_Ensure(); done_ = true; } }
void redo() { if (!done_ && PyEval_ThreadsInitialized()) { save_ = PyEval_SaveThread(); done_ = true; } }
void undo() { if (done_ && PyEval_ThreadsInitialized()) { PyGILState_Release(state_); state_ = PyGILState_UNLOCKED; done_ = false; } }
void undo() { if (done_ && PyEval_ThreadsInitialized()) { PyEval_RestoreThread(save_); save_ = NULL; done_ = false; } }
void motor_env_init_v_multi_thread() { motor_env_init(); if(!PyEval_ThreadsInitialized()) PyEval_InitThreads(); mainThreadState = PyThreadState_Get(); PyEval_ReleaseLock(); }
/* http://docs.python.org/release/2.5.2/ext/callingPython.html */ static void py_guestfs_event_callback_wrapper (guestfs_h *g, void *callback, uint64_t event, int event_handle, int flags, const char *buf, size_t buf_len, const uint64_t *array, size_t array_len) { PyGILState_STATE py_save = PyGILState_UNLOCKED; PyObject *py_callback = callback; PyObject *py_array; PyObject *args; PyObject *a; size_t i; PyObject *py_r; py_array = PyList_New (array_len); for (i = 0; i < array_len; ++i) { a = PyLong_FromLongLong (array[i]); PyList_SET_ITEM (py_array, i, a); } /* XXX As with Perl we don't pass the guestfs_h handle here. */ args = Py_BuildValue ("(Kis#O)", (unsigned PY_LONG_LONG) event, event_handle, buf, buf_len, py_array); if (PyEval_ThreadsInitialized ()) py_save = PyGILState_Ensure (); py_r = PyEval_CallObject (py_callback, args); if (PyEval_ThreadsInitialized ()) PyGILState_Release (py_save); Py_DECREF (args); if (py_r != NULL) Py_DECREF (py_r); else /* Callback threw an exception: print it. */ PyErr_PrintEx (0); }
void singlethreaded::execute_async(unsigned niter) { PyEval_InitThreads(); assert(PyEval_ThreadsInitialized()); boost::mutex::scoped_lock l(iface_mtx); // compute_stack(); //FIXME hack for python based tendrils. scoped_ptr<thread> tmp(new thread(bind(&singlethreaded::execute_impl, this, niter))); tmp->swap(runthread); while(!running()) usleep(5); //TODO FIXME condition variable? }
/* analogue of PyEval_SaveThread() */ BPy_ThreadStatePtr BPY_thread_save(void) { PyThreadState *tstate = PyThreadState_Swap(NULL); /* note: tstate can be NULL when quitting Blender */ if (tstate && PyEval_ThreadsInitialized()) { PyEval_ReleaseLock(); } return (BPy_ThreadStatePtr)tstate; }
static void worldBegin( Renderer &r ) { if ( IECore::staticPointerCast<const IECore::StringData>(r.getOption( "gl:mode" ))->readable() == "deferred" ) { // The deferred render uses multiple threads when rendering procedurals. So we enable threads for python here. // \todo Consider moving this to IECore::Renderer::worldBegin binding (assuming all decent renderers are multithreaded). if ( !PyEval_ThreadsInitialized() ) { PyEval_InitThreads(); } } r.worldBegin(); }
void annoy(int count) { count = std::max(count, 0); if (!PyEval_ThreadsInitialized()) { PyEval_InitThreads(); } #ifdef PRINT_DEBUG_MESSAGES std::cout << "checking thread pool for removal" << std::endl; #endif while(count < threads.size()) { #ifdef PRINT_DEBUG_MESSAGES std::cout << "stopping thread" << std::endl; #endif auto& back = threads.back(); back.second->quit = true; back.first.join(); #ifdef PRINT_DEBUG_MESSAGES std::cout << "removing thread" << std::endl; #endif threads.pop_back(); } #ifdef PRINT_DEBUG_MESSAGES std::cout << "checking thread pool for additions" << std::endl; #endif while(count > threads.size()) { #ifdef PRINT_DEBUG_MESSAGES std::cout << "creating thread" << std::endl; #endif threads.push_back(thread_data{}); #ifdef PRINT_DEBUG_MESSAGES std::cout << "setting thread" << std::endl; #endif auto& back = threads.back(); back.second = std::make_shared<thread_parms>(); back.second->quit = false; #ifdef PRINT_DEBUG_MESSAGES std::cout << "launching thread" << std::endl; #endif back.first = std::thread(worker, back.second); } }
static void uca_camera_init (UcaCamera *camera) { GValue val = {0}; camera->grab_func = NULL; camera->priv = UCA_CAMERA_GET_PRIVATE(camera); camera->priv->cancelling_recording = FALSE; camera->priv->is_recording = FALSE; camera->priv->is_readout = FALSE; camera->priv->transfer_async = FALSE; camera->priv->trigger_source = UCA_CAMERA_TRIGGER_SOURCE_AUTO; camera->priv->trigger_type = UCA_CAMERA_TRIGGER_TYPE_EDGE; camera->priv->buffered = FALSE; camera->priv->num_buffers = 4; camera->priv->ring_buffer = NULL; g_value_init (&val, G_TYPE_UINT); g_value_set_uint (&val, 1); uca_camera_set_property_unit (camera_properties[PROP_SENSOR_WIDTH], UCA_UNIT_PIXEL); uca_camera_set_property_unit (camera_properties[PROP_SENSOR_HEIGHT], UCA_UNIT_PIXEL); uca_camera_set_property_unit (camera_properties[PROP_SENSOR_PIXEL_WIDTH], UCA_UNIT_METER); uca_camera_set_property_unit (camera_properties[PROP_SENSOR_PIXEL_HEIGHT], UCA_UNIT_METER); uca_camera_set_property_unit (camera_properties[PROP_SENSOR_BITDEPTH], UCA_UNIT_COUNT); uca_camera_set_property_unit (camera_properties[PROP_SENSOR_HORIZONTAL_BINNING], UCA_UNIT_PIXEL); uca_camera_set_property_unit (camera_properties[PROP_SENSOR_VERTICAL_BINNING], UCA_UNIT_PIXEL); uca_camera_set_property_unit (camera_properties[PROP_EXPOSURE_TIME], UCA_UNIT_SECOND); uca_camera_set_property_unit (camera_properties[PROP_FRAMES_PER_SECOND], UCA_UNIT_COUNT); uca_camera_set_property_unit (camera_properties[PROP_ROI_X], UCA_UNIT_PIXEL); uca_camera_set_property_unit (camera_properties[PROP_ROI_Y], UCA_UNIT_PIXEL); uca_camera_set_property_unit (camera_properties[PROP_ROI_WIDTH], UCA_UNIT_PIXEL); uca_camera_set_property_unit (camera_properties[PROP_ROI_HEIGHT], UCA_UNIT_PIXEL); uca_camera_set_property_unit (camera_properties[PROP_ROI_WIDTH_MULTIPLIER], UCA_UNIT_PIXEL); uca_camera_set_property_unit (camera_properties[PROP_ROI_HEIGHT_MULTIPLIER], UCA_UNIT_PIXEL); uca_camera_set_property_unit (camera_properties[PROP_RECORDED_FRAMES], UCA_UNIT_COUNT); #ifdef WITH_PYTHON_MULTITHREADING if (!PyEval_ThreadsInitialized ()) { PyEval_InitThreads (); } #endif }
//------------------------------------------------------------------------- // Initialize the Python environment bool HexraysPython_Init(void) { // Already initialized? if ( g_initialized ) return true; if( !init_hexrays_plugin(0) ) { hexdsp = NULL; return false; } { const char *hxver = get_hexrays_version(); msg("hexrays-python: Hex-rays version %s has been detected\n", hxver); } #ifdef Py_DEBUG msg("HexraysPython: Python compiled with DEBUG enabled.\n"); #endif // Start the interpreter Py_Initialize(); if ( !Py_IsInitialized() ) { warning("hexrays-python: Py_Initialize() failed"); return false; } // Enable multi-threading support if ( !PyEval_ThreadsInitialized() ) PyEval_InitThreads(); // Init the SWIG wrapper init_hexrays(); // Import hexrays in python the dirty way until we can do better. PyRun_SimpleString("import hexrays; from hexrays import *;"); g_initialized = true; return true; }
void initrrdtool(void) #endif { PyObject *m; PyDateTime_IMPORT; /* initialize PyDateTime_ functions */ /* make sure that the GIL has been created as we need to aquire it */ if (!PyEval_ThreadsInitialized()) PyEval_InitThreads(); #ifdef HAVE_PY3K m = PyModule_Create(&rrdtoolmodule); #else m = Py_InitModule3("rrdtool", rrdtool_methods, "Python bindings for rrdtool"); #endif if (m == NULL) #ifdef HAVE_PY3K return NULL; #else return; #endif rrdtool_ProgrammingError = PyErr_NewException("rrdtool.ProgrammingError", NULL, NULL); Py_INCREF(rrdtool_ProgrammingError); PyModule_AddObject(m, "ProgrammingError", rrdtool_ProgrammingError); rrdtool_OperationalError = PyErr_NewException("rrdtool.OperationalError", NULL, NULL); Py_INCREF(rrdtool_OperationalError); PyModule_AddObject(m, "OperationalError", rrdtool_OperationalError); PyModule_AddStringConstant(m, "__version__", _version); #ifdef HAVE_PY3K return m; #endif }
NUITKA_MAY_BE_UNUSED static void CONSIDER_THREADING( void ) { // Decrease ticker if ( --_Py_Ticker < 0 ) { _Py_Ticker = _Py_CheckInterval; int res = Py_MakePendingCalls(); if (unlikely( res < 0 )) { throw PythonException(); } PyThreadState *tstate = PyThreadState_GET(); assert( tstate ); if ( PyEval_ThreadsInitialized() ) { // Release and acquire the GIL, it's very inefficient, because we // don't even know if it makes sense to do it. A controlling thread // should be used to determine if it's needed at all. PyEval_SaveThread(); PyEval_AcquireThread( tstate ); } if (unlikely( tstate->async_exc != NULL )) { PyObjectTemporary tmp_async_exc( tstate->async_exc ); tstate->async_exc = NULL; throw PythonException( tmp_async_exc.asObject0() ); } } }
/** * Should be called before executing a script */ void XBPython::Initialize() { CLog::Log(LOGINFO, "initializing python engine. "); CSingleLock lock(m_critSection); m_iDllScriptCounter++; if (!m_bInitialized) { // first we check if all necessary files are installed #ifndef _LINUX if(!FileExist("special://xbmc/system/python/DLLs/_socket.pyd") || !FileExist("special://xbmc/system/python/DLLs/_ssl.pyd") || !FileExist("special://xbmc/system/python/DLLs/bz2.pyd") || !FileExist("special://xbmc/system/python/DLLs/pyexpat.pyd") || !FileExist("special://xbmc/system/python/DLLs/select.pyd") || !FileExist("special://xbmc/system/python/DLLs/unicodedata.pyd")) { CLog::Log(LOGERROR, "Python: Missing files, unable to execute script"); Finalize(); return; } #endif // Info about interesting python envvars available // at http://docs.python.org/using/cmdline.html#environment-variables #if !defined(_WIN32) /* PYTHONOPTIMIZE is set off intentionally when using external Python. Reason for this is because we cannot be sure what version of Python was used to compile the various Python object files (i.e. .pyo, .pyc, etc.). */ // check if we are running as real xbmc.app or just binary if (!CUtil::GetFrameworksPath(true).IsEmpty()) { // using external python, it's build looking for xxx/lib/python2.6 // so point it to frameworks which is where python2.6 is located setenv("PYTHONHOME", _P("special://frameworks").c_str(), 1); setenv("PYTHONPATH", _P("special://frameworks").c_str(), 1); CLog::Log(LOGDEBUG, "PYTHONHOME -> %s", _P("special://frameworks").c_str()); CLog::Log(LOGDEBUG, "PYTHONPATH -> %s", _P("special://frameworks").c_str()); } setenv("PYTHONCASEOK", "1", 1); //This line should really be removed #elif defined(_WIN32) // because the third party build of python is compiled with vs2008 we need // a hack to set the PYTHONPATH // buf is corrupted after putenv and might need a strdup but it seems to // work this way CStdString buf; buf = "PYTHONPATH=" + _P("special://xbmc/system/python/DLLs") + ";" + _P("special://xbmc/system/python/Lib"); pgwin32_putenv(buf.c_str()); buf = "PYTHONOPTIMIZE=1"; pgwin32_putenv(buf.c_str()); buf = "PYTHONHOME=" + _P("special://xbmc/system/python"); pgwin32_putenv(buf.c_str()); buf = "OS=win32"; pgwin32_putenv(buf.c_str()); #endif if (PyEval_ThreadsInitialized()) PyEval_AcquireLock(); else PyEval_InitThreads(); Py_Initialize(); PyEval_ReleaseLock(); // If this is not the first time we initialize Python, the interpreter // lock already exists and we need to lock it as PyEval_InitThreads // would not do that in that case. PyEval_AcquireLock(); char* python_argv[1] = { (char*)"" } ; PySys_SetArgv(1, python_argv); InitXBMCTypes(); InitGUITypes(); InitPluginTypes(); InitAddonTypes(); if (!(m_mainThreadState = PyThreadState_Get())) CLog::Log(LOGERROR, "Python threadstate is NULL."); PyEval_ReleaseLock(); m_bInitialized = true; } }
PyMODINIT_FUNC initGPIO(void) #endif { int i; PyObject *module = NULL; #if PY_MAJOR_VERSION > 2 if ((module = PyModule_Create(&rpigpiomodule)) == NULL) return NULL; #else if ((module = Py_InitModule3("RPi.GPIO", rpi_gpio_methods, moduledocstring)) == NULL) return; #endif define_constants(module); for (i=0; i<54; i++) gpio_direction[i] = -1; // detect board revision and set up accordingly revision = get_rpi_revision(); if (revision == -1) { PyErr_SetString(PyExc_RuntimeError, "This module can only be run on a Raspberry Pi!"); setup_error = 1; #if PY_MAJOR_VERSION > 2 return NULL; #else return; #endif } else if (revision == 1) { pin_to_gpio = &pin_to_gpio_rev1; } else if (revision == 2) { pin_to_gpio = &pin_to_gpio_rev2; } else { // assume model B+ pin_to_gpio = &pin_to_gpio_rev3; } rpi_revision = Py_BuildValue("i", revision); PyModule_AddObject(module, "RPI_REVISION", rpi_revision); // Add PWM class if (PWM_init_PWMType() == NULL) #if PY_MAJOR_VERSION > 2 return NULL; #else return; #endif Py_INCREF(&PWMType); PyModule_AddObject(module, "PWM", (PyObject*)&PWMType); if (!PyEval_ThreadsInitialized()) PyEval_InitThreads(); // register exit functions - last declared is called first if (Py_AtExit(cleanup) != 0) { setup_error = 1; cleanup(); #if PY_MAJOR_VERSION > 2 return NULL; #else return; #endif } if (Py_AtExit(event_cleanup_all) != 0) { setup_error = 1; cleanup(); #if PY_MAJOR_VERSION > 2 return NULL; #else return; #endif } #if PY_MAJOR_VERSION > 2 return module; #else return; #endif }
static int _cffi_carefully_make_gil(void) { /* This does the basic initialization of Python. It can be called completely concurrently from unrelated threads. It assumes that we don't hold the GIL before (if it exists), and we don't hold it afterwards. What it really does is completely different in Python 2 and Python 3. Python 2 ======== Initialize the GIL, without initializing the rest of Python, by calling PyEval_InitThreads(). PyEval_InitThreads() must not be called concurrently at all. So we use a global variable as a simple spin lock. This global variable must be from 'libpythonX.Y.so', not from this cffi-based extension module, because it must be shared from different cffi-based extension modules. We choose _PyParser_TokenNames[0] as a completely arbitrary pointer value that is never written to. The default is to point to the string "ENDMARKER". We change it temporarily to point to the next character in that string. (Yes, I know it's REALLY obscure.) Python 3 ======== In Python 3, PyEval_InitThreads() cannot be called before Py_InitializeEx() any more. So this function calls Py_InitializeEx() first. It uses the same obscure logic to make sure we never call it concurrently. Arguably, this is less good on the spinlock, because Py_InitializeEx() takes much longer to run than PyEval_InitThreads(). But I didn't find a way around it. */ #ifdef WITH_THREAD char *volatile *lock = (char *volatile *)_PyParser_TokenNames; char *old_value; while (1) { /* spin loop */ old_value = *lock; if (old_value[0] == 'E') { assert(old_value[1] == 'N'); if (cffi_compare_and_swap(lock, old_value, old_value + 1)) break; } else { assert(old_value[0] == 'N'); /* should ideally do a spin loop instruction here, but hard to do it portably and doesn't really matter I think: PyEval_InitThreads() should be very fast, and this is only run at start-up anyway. */ } } #endif #if PY_MAJOR_VERSION >= 3 /* Python 3: call Py_InitializeEx() */ { PyGILState_STATE state = PyGILState_UNLOCKED; if (!Py_IsInitialized()) _cffi_py_initialize(); else state = PyGILState_Ensure(); PyEval_InitThreads(); PyGILState_Release(state); } #else /* Python 2: call PyEval_InitThreads() */ # ifdef WITH_THREAD if (!PyEval_ThreadsInitialized()) { PyEval_InitThreads(); /* makes the GIL */ PyEval_ReleaseLock(); /* then release it */ } /* else: there is already a GIL, but we still needed to do the spinlock dance to make sure that we see it as fully ready */ # endif #endif #ifdef WITH_THREAD /* release the lock */ while (!cffi_compare_and_swap(lock, old_value + 1, old_value)) ; #endif return 0; }
void initlibevwrapper(void) #endif { PyObject *module = NULL; if (PyType_Ready(&libevwrapper_LoopType) < 0) INITERROR; libevwrapper_IOType.tp_new = PyType_GenericNew; if (PyType_Ready(&libevwrapper_IOType) < 0) INITERROR; libevwrapper_PrepareType.tp_new = PyType_GenericNew; if (PyType_Ready(&libevwrapper_PrepareType) < 0) INITERROR; libevwrapper_AsyncType.tp_new = PyType_GenericNew; if (PyType_Ready(&libevwrapper_AsyncType) < 0) INITERROR; # if PY_MAJOR_VERSION >= 3 module = PyModule_Create(&moduledef); # else module = Py_InitModule3("libevwrapper", module_methods, module_doc); # endif if (module == NULL) INITERROR; if (PyModule_AddIntConstant(module, "EV_READ", EV_READ) == -1) INITERROR; if (PyModule_AddIntConstant(module, "EV_WRITE", EV_WRITE) == -1) INITERROR; if (PyModule_AddIntConstant(module, "EV_ERROR", EV_ERROR) == -1) INITERROR; Py_INCREF(&libevwrapper_LoopType); if (PyModule_AddObject(module, "Loop", (PyObject *)&libevwrapper_LoopType) == -1) INITERROR; Py_INCREF(&libevwrapper_IOType); if (PyModule_AddObject(module, "IO", (PyObject *)&libevwrapper_IOType) == -1) INITERROR; Py_INCREF(&libevwrapper_PrepareType); if (PyModule_AddObject(module, "Prepare", (PyObject *)&libevwrapper_PrepareType) == -1) INITERROR; Py_INCREF(&libevwrapper_AsyncType); if (PyModule_AddObject(module, "Async", (PyObject *)&libevwrapper_AsyncType) == -1) INITERROR; if (!PyEval_ThreadsInitialized()) { PyEval_InitThreads(); } #if PY_MAJOR_VERSION >= 3 return module; #endif }
PyMODINIT_FUNC initGPIO(void) #endif { int i; PyObject *module = NULL; char cpuRev[1024] = {'\0'}; #if PY_MAJOR_VERSION > 2 if ((module = PyModule_Create(&lmkgpiomodule)) == NULL) return NULL; #else if ((module = Py_InitModule3("LMK.GPIO", lmk_gpio_methods, moduledocstring)) == NULL) return; #endif if (get_cpuinfo_revision(cpuRev) == NULL) #if PY_MAJOR_VERSION > 2 return NULL; #else return; #endif revision = get_lmk_revision(); debug("BOARD: revision(%d)\n",revision); define_constants(module); for (i=0; i<256; i++) gpio_direction[i] = -1; if (revision == -1) { PyErr_SetString(PyExc_RuntimeError, "This module can only be run on a Raspberry Pi!"); setup_error = 1; #if PY_MAJOR_VERSION > 2 return NULL; #else return; #endif } lmk_revision = Py_BuildValue("i", revision); PyModule_AddObject(module, "LMK_REVISION", lmk_revision); // Add PWM class if (PWM_init_PWMType() == NULL){ #if PY_MAJOR_VERSION > 2 return NULL; #else return; #endif } Py_INCREF(&PWMType); PyModule_AddObject(module, "PWM", (PyObject*)&PWMType); if (!PyEval_ThreadsInitialized()){ PyEval_InitThreads(); } //Initialized only once if (mmap_gpio_mem()) #if PY_MAJOR_VERSION > 2 return NULL; #else return; #endif // register exit functions - last declared is called first if (Py_AtExit(cleanup) != 0) { setup_error = 1; cleanup(); #if PY_MAJOR_VERSION > 2 return NULL; #else return; #endif } if (Py_AtExit(event_cleanup_all) != 0) { setup_error = 1; cleanup(); #if PY_MAJOR_VERSION > 2 return NULL; #else return; #endif } #if PY_MAJOR_VERSION > 2 return module; #else return; #endif }