Python Programming (three operating modes of Python development) "Go"

Source: Internet
Author: User

Transferred from: http://blog.csdn.net/feixiaoxing/article/details/53980886

Copyright Notice: This article for Bo Master original article, without Bo Master permission not reproduced. Catalog (?) [-] Single cycle mode multithreaded mode reactor mode "declaration: Copyright, welcome reprint, please do not use for commercial purposes. Contact box: feixiaoxing @163. com python, as a scripting language, has a wide range of uses. Some students used algorithm development, some to verify the logic, and some as glue language, use it to glue the whole system process. In any case, how you use Python depends on your own business scenario and on your own Python application capabilities. Personally, I think Python can be used for both business development and prototype development. In general, Python runs primarily under these three modes. 1Single cycle mode single cycle mode uses the most, also the simplest, and of course the most stable. Why, because the single cycle of the code is rarely written, the chance of error is less, so generally as long as the interface is written, the opportunity to make mistakes is still very low. Of course, we are not saying that the single cycle is useless, on the contrary. Single-cycle mode is one of the most common patterns we use. This development is especially suitable for small tools, small applications, and small scenes. #!/usr/bin/pythonimport osimport sysimport reimport signalimport timeg_exit=0def sig_process (SIG, frame):Globalg_exit g_exit=1Print'Catch Signal'def main ():Globalg_exit signal.signal (signal. SIGINT, sig_process) while 0==G_exit:time.sleep (1)        " "Module Process Code" " if__name__ = ='__main__': Main ()2Multithreaded mode multithreaded mode is often used in those situations where it is easy to block. such as multi-threaded client read and write, multithreaded Web Access and so on. One of the features of multithreading here is that each thread is created by the client. A simple example is the server socket, a socket to create a thread, so if there are multiple users, there are multiple thread concurrent connection. This is a simple way to use quickly, the disadvantage is that all business can be executed concurrently, the global data protection is cumbersome. #!/usr/bin/pythonimport osimport sysimport reimport signalimport timeimport threadingg_exit=0def run_thread ():GlobalG_exit while 0==G_exit:time.sleep (1)        " "         Dojobs per thread" "def sig_process (SIG, frame):Globalg_exit g_exit=1def main ():Globalg_exit signal.signal (signal. SIGINT, sig_process) g_threads= []     forIinchRange4): TD= Threading. Thread (target =run_thread) Td.start () G_threads.append (TD) while 0==G_exit:time.sleep (1)     forIinchRange4): G_threads[i].join ()if__name__ = ='__main__': Main ()3. Reactor mode reactor mode, not complicated, simply, is the use of multithreading to deal with each of the business. If a business has already been processed by one thread, the other thread will not be able to handle the business again. In this way, it is equivalent to solving a problem, which is what we said in the previous lock problem. So for developers of this model, writing a business is actually a simple matter, because all he has to focus on is his own acre of land. Before the cloud wind students write Skynet is such a pattern, but it uses C+Lua to develop.  In fact, as long as the understanding of the reactor model itself, with what language development is not important, the key is to understand the essence of reactor can be. If it's written in code, it should be, #!/usr/bin/pythonimport osimport sysimport reimport timeimport signalimport threadingg_num=4G_exit=0g_threads=[]g_sem=[]g_lock=Threading. Lock () g_event={}def add_event (name, data):GlobalG_lockGlobalg_eventif "'==Name:returnG_lock.acquire ()ifNameinchg_event:g_event[name].append (data) g_lock.release ()returnG_event[name]= []    " "    0Means idle,1means busy" "G_event[name].append (0) g_event[name].append (data) g_lock.release () def get_event (name):GlobalG_lockGlobalg_event G_lock.acquire ()if "'!=Name:if[] !=G_event[name]:if 1!=Len (G_event[name]): Data= g_event[name][1] del g_event[name][1] G_lock.release ()returnName, DataElse: g_event[name][0] =0     forKinchg_event:if 1==Len (g_event[k]):Continue        if 1= = g_event[k][0]:            Continueg_event[k][0] =1Data= g_event[k][1] del g_event[k][1] G_lock.release ()returnk, Data g_lock.release ()return "', -1def sig_process (SIG, frame):Globalg_exit g_exit=1Print'Catch Signal'def run_thread (num):GlobalG_exitGlobalG_semGlobalG_lock name="'Data= -1     while 0==G_exit:g_sem[num].acquire () whiletrue:name, Data=get_event (name)if "'==Name: BreakG_lock.acquire () print name, Data g_lock.release () def test_thread ():GlobalG_exit while 0==G_exit: forIinchRange -): Add_event ('1', (I <<2) +0) add_event ('2', (I <<2) +1) add_event ('3', (I <<2) +2) add_event ('4', (I <<2) +3) Time.sleep (1) def main ():GlobalG_exitGlobalG_numGlobalg_threadsGlobalG_sem signal.signal (signal. SIGINT, sig_process) forIinchRange (g_num): Sem= Threading. Semaphore (0) G_sem.append (SEM) TD= Threading. Thread (Target=run_thread, args=(i,)) Td.start () G_threads.append (TD)" "test thread to give data" "Test = Threading. Thread (target=test_thread) Test.start () while 0==G_exit: forIinchRange (G_num): G_sem[i].release () time.sleep (1)    " "Call all thread to close" "     forIinchRange (G_num): G_sem[i].release () forIinchRange (G_num): G_threads[i].join () test.join () print'Exit Now'" "entry" "if__name__ = ='__main__': Main ()

Python Programming (three operating modes of Python development) "Go"

Related Article

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.