Three running modes developed by python

Source: Internet
Author: User
This article mainly introduces the detailed information about the three running modes developed by python. For more information about the three running modes developed by python, see the following article, for more information, see

Three running modes of Python

As a scripting language, Python is widely used. Some are used for algorithm development, some are used to verify the logic, and some are used as the glue language to bond the entire system process. In any case, how to use python depends on your own business scenario and your own python application capabilities. Personally, I think python can be used for both business development and product prototype development. generally, python runs in the following three modes.

1. single cycle mode

The single-cycle mode is the most used, which is also the simplest and most stable. Why? because the code in a single loop is rarely written and there are fewer errors, the chances of making mistakes are usually very low as long as the interface is correct. Of course, we do not mean that a single loop is useless, just the opposite. The single loop mode is the most frequently used mode. This kind of development is especially suitable for some gadgets, small applications, and small scenarios.

#!/usr/bin/pythonimport osimport sysimport reimport signalimport timeg_exit = 0def sig_process(sig, frame):  global g_exit  g_exit = 1  print 'catch signal'def main():  global g_exit  signal.signal(signal.SIGINT, sig_process)  while 0 == g_exit:    time.sleep(1)    '''    module process code    ''' if __name__ == '__main__':  main()

2. multithreading

Multithreading is often used in scenarios that are prone to blocking. For example, multi-threaded client read/write and multi-threaded web access. Multithreading has a feature, that is, every thread is created according to the client. A simple example is a server socket. a socket is used to create a thread. if multiple users exist, multiple threads can be connected concurrently. This method is relatively simple and can be used quickly. The disadvantage is that all services may be executed concurrently, and global data protection is troublesome.

#!/usr/bin/pythonimport osimport sysimport reimport signalimport timeimport threadingg_exit=0def run_thread():  global g_exit  while 0 == g_exit:    time.sleep(1)    '''    do jobs per thread    '''def sig_process(sig, frame):  global g_exit  g_exit = 1def main():  global g_exit  signal.signal(signal.SIGINT, sig_process)  g_threads = []  for i in range(4):    td = threading.Thread(target = run_thread)    td.start()    g_threads.append(td)  while 0 == g_exit:    time.sleep(1)  for i in range(4):    g_threads[i].join()if __name__ == '__main__':  main()

3. reactor mode

The reactor mode is not complex. Simply put, multithreading is used to process every business. If a service has been processed by a thread, other threads cannot process the service again. In this way, it solves a problem, that is, the lock we mentioned above. Therefore, for developers of this model, writing business is actually a simple task, because all they want to do is to focus on their own one acre of land. Previously, skynet compiled by Yunfeng was developed using c + lua. In fact, as long as you understand the reactor mode itself, it is not important to use any language for Development. the key is to understand the essence of the reactor.

If the code is written, it should be like this,

#!/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):  global g_lock  global g_event  if '' == name:    return  g_lock.acquire()  if name in g_event:    g_event[name].append(data)    g_lock.release()    return  g_event[name] = []  '''  0 means idle, 1 means busy  '''  g_event[name].append(0)  g_event[name].append(data)  g_lock.release()def get_event(name):  global g_lock  global g_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()        return name, data      else:        g_event[name][0] = 0  for k in g_event:    if 1 == len(g_event[k]):      continue    if 1 == g_event[k][0]:      continue    g_event[k][0] =1    data = g_event[k][1]    del g_event[k][1]    g_lock.release()    return k, data  g_lock.release()  return '', -1def sig_process(sig, frame):  global g_exit  g_exit =1  print 'catch signal'def run_thread(num):  global g_exit  global g_sem  global g_lock  name = ''  data = -1  while 0 == g_exit:    g_sem[num].acquire()    while True:       name, data = get_event(name)      if '' == name:        break      g_lock.acquire()      print name, data      g_lock.release()def test_thread():  global g_exit  while 0 == g_exit:    for i in range(100):      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():  global g_exit  global g_num  global g_threads  global g_sem  signal.signal(signal.SIGINT, sig_process)  for i in range(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:    for i in range(g_num):      g_sem[i].release()    time.sleep(1)  '''  call all thread to close  '''  for i in range(g_num):    g_sem[i].release()  for i in range(g_num):    g_threads[i].join()  test.join()  print 'exit now''''entry'''if __name__ == '__main__':  main()

Thank you for reading this article. I hope it will help you. thank you for your support for this site!

For more information about the three running modes developed by python, see The PHP Chinese network!

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.