Detailed introduction to python multi-thread applications

Source: Internet
Author: User

When using python multithreading, you need to pay attention to a lot of things. In fact, you only need to master these technical segments to ensure the integrity of this application. Next, let's take a look at how to perform the operation.

Today, I read about how to securely call multiple threads in python in multithreading applications in the last day. At the beginning, I thought it was a big fight, the Global Interpreter Lock and Thread State of the python language were a little dizzy. Later, I went through various articles and help documents for mutual reference, we found that for versions 2.4/2.5, we provided PyGILState_Ensure and PyGILState_Release.

1. Define an encapsulation class to ensure pair use of PyGILState_Ensure and PyGILState_Release, which can be nested.

 
 
  1. #include <python.h> 
  2. class PyThreadStateLock  
  3. {  
  4. public:  
  5. PyThreadStateLock(void)  
  6. {  
  7. state = PyGILState_Ensure( );  
  8. }  
  9. ~PyThreadStateLock(void)  
  10. {  
  11. PyGILState_Release( state );  
  12. }  
  13. private:  
  14. PyGILState_STATE state;  
  15. };  


2. In the main thread, this process

// Initialization
Py_Initialize ();
// Initialization thread support
PyEval_InitThreads ();
// Run the command before starting the child thread. To release the global lock obtained by PyEval_InitThreads, the Child thread may not be able to obtain the global lock.
PyEval_ReleaseThread (PyThreadState_Get ());

// Other processes, such as promoter threads
......

// Ensure that all sub-thread calls are completed
PyGILState_Ensure ();
Py_Finalize ();
// You cannot call any python API later

The above is a detailed introduction to python multithreading. Hope to help you.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.