Home  >  Article  >  Backend Development  >  Detailed introduction to the three operating modes developed by python

Detailed introduction to the three operating modes developed by python

高洛峰
高洛峰Original
2017-02-14 14:03:191416browse

This article mainly introduces relevant information on the detailed introduction of the three operating modes developed by Python. Friends in need can refer to

Three operating modes of Python

Python, as a scripting language, is used in a wide range of applications. Some students use it to develop algorithms, some use it to verify logic, and some use it as a glue language to bind the entire system process. In any case, how to use python depends on both your own business scenarios and your own python application capabilities. Personally, I think python can be used for both business development and product prototype development. Generally speaking, python mainly operates in the following three modes.

1. Single loop mode

The single loop mode is the most used, the simplest, and of course the most stable. Why? Because less code is written in a single loop, and there are fewer opportunities for errors. Therefore, as long as the interface is written correctly, the chance of errors is generally very low. Of course, we are not saying that a single loop is useless, quite the contrary. Single loop mode is the mode we use most often. This kind of development is particularly suitable for some gadgets, small applications, and small scenes.

#!/usr/bin/python
import os
import sys
import re
import signal
import time

g_exit = 0

def 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. Multi-threaded mode

Multi-threaded mode is often used in situations that are prone to blocking. For example, multi-threaded client reading and writing, multi-threaded web access, etc. One feature of multi-threading here is that each thread is created according to the client. A simple example is a server socket. Use a socket to create a thread, so that if there are multiple users, there will be multiple threads connecting concurrently. This method is relatively simple and fast to use. The disadvantage is that all businesses may be executed concurrently, and global data protection is very troublesome.

#!/usr/bin/python
import os
import sys
import re
import signal
import time
import threading

g_exit=0

def 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 = 1

def 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

Reactor mode is not complicated. To put it simply, it uses multi-threading. to handle every business. If a business has been processed by a thread, other threads cannot process the business again. In this way, it is equivalent to solving a problem, which is the lock problem we mentioned earlier. Therefore, for developers in this model, writing business is actually a simple matter, because all he has to focus on is his own one-third of an acre. The skynet written by Yunfeng before was of such a model, but it was developed using C+lua. In fact, as long as you understand the reactor pattern itself, it doesn't matter what language you use for development. The key is to understand the essence of reactor.

python 开发的三种运行模式详细介绍

If written as code, it should be like this,

#!/usr/bin/python

import os
import sys
import re
import time
import signal
import threading

g_num = 4
g_exit =0
g_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 '', -1

def 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(&#39;1&#39;, (i << 2) + 0)
      add_event(&#39;2&#39;, (i << 2) + 1)
      add_event(&#39;3&#39;, (i << 2) + 2)
      add_event(&#39;4&#39;, (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)

  &#39;&#39;&#39;
  test thread to give data
  &#39;&#39;&#39;
  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)

  &#39;&#39;&#39;
  call all thread to close
  &#39;&#39;&#39;
  for i in range(g_num):
    g_sem[i].release()

  for i in range(g_num):
    g_threads[i].join()

  test.join()
  print &#39;exit now&#39;

&#39;&#39;&#39;
entry
&#39;&#39;&#39;
if __name__ == &#39;__main__&#39;:
  main()

Thanks for reading, I hope it helps everyone, thank you for your support of this site!

For more detailed introduction to the three operating modes of python development and related articles, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn