Multiple processes

Almost the same as multithreading, but more resources, so not the more the better

import time 
import multiprocessing

def test1() :
  while True:
    print('1 -- -- -- -- -- -- -- -- -- -- -- -- --')
    time.sleep(1)


def test2() :
  while True:
    print('2 -- -- -- -- -- -- -- -- -- -- -- -- --')
    time.sleep(1)
  

def main() :
  p1 = multiprocessing.Process(target=test1)
  p2 = multiprocessing.Process(target=test2)
  p1.start()
  p2.start()


if __name__ == '__main__': 
    main()
    
Copy the code

! [image – 20200502115746746] (# iterator

from collections import Iterable,Iterator
import time
# class classIterator():
# def __init__(self,obj):
# self.obj = obj
# self.current_num = 0
# def __iter__(self):
# pass
    
# def __next__(self):
# if self.current_num
# ret = self.obj.names[self.current_num]
# self.current_num+=1
# return ret
# else:
# raise StopIteration


class Classmate(object) :
    def __init__(self) :
        self.names = list()
        self.current_num = 0
    
    def add(self,name) :
        self.names.append(name)

    def __iter__(self) :
        If you want an object to be iterable, using for, you must implement the __iter__ method.  
        return self
    def __next__(self) :
        if self.current_num<len(self.names):
            ret = self.names[self.current_num]
            self.current_num+=1
            return ret
        else:
            raise StopIteration

classmate = Classmate()
classmate.add('Lao wang')
classmate.add('pharaoh 2')
classmate.add('pharaoh 3')


# classmate_iterator = iter(classmate) 
# print(' check whether classmate can iterate :',isinstance(classmate,Iterable))
# print(' check whether classmate is an Iterator :',isinstance(classmate_iterator,Iterator)
# print(next(classmate_iterator)) #

for name in classmate: 
    print(name)
    time.sleep(1)

Copy the code

The generator

Generators are special iterators

The first way

[x*2 for x in range(10)] can be generatedlistReplace the brackets with the braces to make an iteratorlistIt takes up space, but iterators are just a way of recording generated data, and it doesn't take up much space, so that's what the iterator is relative tolistThe advantages ofCopy the code

The second way

The function contains yield

Greenlet is an updated version of yield /image-20200502115746746.png)

Interprocess communication

Using a queue

The process of pool

Program creation and destruction need a lot of resources, if the use of process pool can reduce the creation and destruction, to achieve reuse

thread

Create a thread from a function (you can view the number of threads)

import time
import threading


def sing() :
    for i in range(5) :print('singing')
        time.sleep(1)


def dance() :
    for i in range(0.10) :print('dancing')
        time.sleep(1)



def main() :
    t1 = threading.Thread(target=sing)
    t2 = threading.Thread(target=dance)
    t1.start()
    t2.start() 
    while  True:
      print(threading.enumerate(),len(threading.enumerate()))
      time.sleep(1)
      if len(threading.enumerate< = ())1:
        print(threading.enumerate(),len(threading.enumerate()))
        print('End of program')
        break
    


if __name__ == '__main__':
    main()

Copy the code

Function and the cords

Create threads by creating objects in class

The run method must be defined. The run method is executed at start. Using threads in a class is ideal for complex threads, such as using multiple functions to use threads, and passing arguments

from time import * 
import threading


class setInterval(threading.Thread) :
  
  def __init__(self,func,time) :
    super().__init__()
    self.time = time
    self.bool = True
    self.func =func
    self.i =0

  def stop(self) :
    print('the end')
    self.bool = False

  def run(self) :
    while self.bool:
      sleep(1)
      self.func()
      
def myfunc() :
  print('test')
t = setInterval(myfunc,1)
t.start()

def clearInterval(t) :
  t.stop()

sleep(5)
clearInterval(t)
Copy the code

Multiple threads share global variables

Of course, global variables are accessible to all functions. What else is there to explain that

Sharing existing problems (resource competition)

Multiple threads working on global variables at the same time can cause problems. If more than two threads work on a global variable at the same time, one of them may fail

Solution – Mutex

The less code you lock, the better

coroutines

The iterator

from collections import Iterable,Iterator
import time
# class classIterator():
# def __init__(self,obj):
# self.obj = obj
# self.current_num = 0
# def __iter__(self):
# pass
    
# def __next__(self):
# if self.current_num
# ret = self.obj.names[self.current_num]
# self.current_num+=1
# return ret
# else:
# raise StopIteration


class Classmate(object) :
    def __init__(self) :
        self.names = list()
        self.current_num = 0
    
    def add(self,name) :
        self.names.append(name)

    def __iter__(self) :
        If you want an object to be iterable, using for, you must implement the __iter__ method.  
        return self
    def __next__(self) :
        if self.current_num<len(self.names):
            ret = self.names[self.current_num]
            self.current_num+=1
            return ret
        else:
            raise StopIteration

classmate = Classmate()
classmate.add('Lao wang')
classmate.add('pharaoh 2')
classmate.add('pharaoh 3')


# classmate_iterator = iter(classmate) 
# print(' check whether classmate can iterate :',isinstance(classmate,Iterable))
# print(' check whether classmate is an Iterator :',isinstance(classmate_iterator,Iterator)
# print(next(classmate_iterator)) #

for name in classmate: 
    print(name)
    time.sleep(1)

Copy the code

The generator

Generators are special iterators

The first way

[x*2 for x in range(10)] can be generatedlistReplace the brackets with the braces to make an iteratorlistIt takes up space, but iterators are just a way of recording generated data, and it doesn't take up much space, so that's what the iterator is relative tolistThe advantages ofCopy the code

The second way

The function contains yield

Greenlet is an updated version of Yield