西维蜀黍

【Python】线程 - 多线程(Multi-threading)

Python 多线程

Python中使用线程有两种方式:函数或者用类来包装线程对象。

创建新线程的办法

start_new_thread 函数 - 创建新线程

thread.start_new_thread ( function, args[, kwargs] )

参数说明:

  • function - 线程函数。
  • args - 传递给线程函数的参数,他必须是个tuple类型。
  • kwargs - 可选参数。
#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
import thread
import time
 
# 为线程定义一个函数
def print_time( threadName, delay):
   count = 0
   while count < 5:
      time.sleep(delay)
      count += 1
      print "%s: %s" % ( threadName, time.ctime(time.time()) )
 
# 创建两个线程
try:
   thread.start_new_thread( print_time, ("Thread-1", 2, ) )
   thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
   print "Error: unable to start thread"
 
while 1:
   pass

继承线程类 - 创建线程

Python 提供了Thread类来处理线程,Thread类提供了以下方法:

  • run(): 用以表示线程活动的方法。
  • start():启动线程活动。
  • join([time]) :等待至线程中止。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者抛出未处理的异常-或者是可选的超时发生。
  • isAlive():返回线程是否活动的。
  • getName():返回线程名。
  • setName() :设置线程名。

使用Threading模块创建线程,直接从threading.Thread类继承,然后重写__init__方法和run方法:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
import threading
import time
 
exitFlag = 0
 
class myThread (threading.Thread):   #继承父类threading.Thread
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.counter = counter
    def run(self):                   #把要执行的代码写到run函数里面 线程在创建后会直接运行run函数 
        print "Starting " + self.name
        print_time(self.name, self.counter, 5)
        print "Exiting " + self.name
 
def print_time(threadName, delay, counter):
    while counter:
        if exitFlag:
            (threading.Thread).exit()
        time.sleep(delay)
        print "%s: %s" % (threadName, time.ctime(time.time()))
        counter -= 1
 
# 创建新线程
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
 
# 开启线程
thread1.start()
thread2.start()
 
print "Exiting Main Thread"

或者,把一个函数传入并创建Thread实例,然后调用start()开始执行:

import time, threading

# 新线程执行的代码:
def loop():
    print('thread %s is running...' % threading.current_thread().name)
    n = 0
    while n < 5:
        n = n + 1
        print('thread %s >>> %s' % (threading.current_thread().name, n))
        time.sleep(1)
    print('thread %s ended.' % threading.current_thread().name)

print('thread %s is running...' % threading.current_thread().name)
t = threading.Thread(target=loop, name='LoopThread')
t.start()
t.join()
print('thread %s ended.' % threading.current_thread().name)
  ...


【Python】线程 - 多进程

Background

Unix/Linux操作系统提供了一个fork()系统调用,它非常特殊。

对普通函数的调用,调用一次,返回一次。

但是,调用fork()一次,返回两次,因为操作系统自动把当前进程(称为父进程)复制了一份(称为子进程),然后,分别在父进程和子进程内返回。

子进程永远返回0,而父进程返回子进程的ID。这样做的理由是,一个父进程可以fork出很多子进程,所以,父进程要记下每个子进程的ID,而子进程只需要调用getppid()就可以拿到父进程的ID。

Python的os模块封装了常见的系统调用,其中就包括fork,可以在Python程序中轻松创建子进程:

import os

print('Process (%s) start...' % os.getpid())
# Only works on Unix/Linux/Mac:
pid = os.fork()
if pid == 0:
    print('I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid()))
else:
    print('I (%s) just created a child process (%s).' % (os.getpid(), pid))

运行结果如下:

Process (876) start...
I (876) just created a child process (877).
I am child process (877) and my parent is 876.

由于Windows没有fork调用,上面的代码在Windows上无法运行。而Mac系统是基于BSD(Unix的一种)内核,所以,在Mac下运行是没有问题的,推荐大家用Mac学Python!

有了fork调用,一个进程在接到新任务时就可以复制出一个子进程来处理新任务,常见的Apache服务器就是由父进程监听端口,每当有新的http请求时,就fork出子进程来处理新的http请求。

  ...


【Engineering】Encode

ASCII is a simple form of Unicode text, but just one of many possible encodings and alphabets. Text from non-English-speaking sources may use very different letters, and may be encoded very differently when stored in files.

ASCII

ASCII, abbreviated from American Standard Code for Information Interchange, is a character encoding standard for electronic communication. ASCII codes represent text in computers, telecommunications equipment, and other devices. Most modern character-encoding schemes are based on ASCII, although they support many additional characters.

  ...


【Python】Basics - Simple Data Types - String

String

  • Strings in Python can be enclosed in either single quotes (’) or double quotes ("), or three of each (’’’ or “”")
  • Double quoted strings can contain single quotes inside them, as in "Bruce's beard"
  • and single quoted strings can have double quotes inside them, as in 'The knights who say "Ni!"'
  • triple quoted strings: strings enclosed with three occurrences of either quote symbol (either single or double quotes)

  • can even span multiple lines

  ...


【Python】Basics - Variables

Assignment statement

Assignment statement gives a value to a variable:

  • assignment token: =
  • equals: ==

Ask the interpreter to evaluate a variable

  ...


【Python】Basics - Exceptions

Using try-except Blocks

When you think an error may occur, you can write a try- except block to handle the exception that might be raised. You tell Python to try running some code, and you tell it what to do if the code results in a particular kind of exception.

Here’s what a try- except block for handling the ZeroDivisionError exception looks like:

try:
		print(5/0) 
except ZeroDivisionError:
		print("You can't divide by zero!")
  ...


【Python】IO - WriteFiles

Writing to an Empty File

To write text to a file, you need to call open() with a second argument telling Python that you want to write to the file. To see how this works, let’s write a simple message and store it in a file instead of printing it to the screen:

filename = 'programming.txt'

with open(filename, 'w') as file_object:
		file_object.write("I love programming.")

The second argument, ‘w’, tells Python that we want to open the file in write mode. You can open a file in read mode (‘r’), write mode (‘w’), append mode (‘a’), or a mode that allows you to read and write to the file (‘r+’). If you omit the mode argument, Python opens the file in read-only mode by default.

  ...


【Python】IO - ReadFiles

Reading an Entire File

To begin, we need a file with a few lines of text in it. Let’s start with a file that contains pi to 30 decimal places with 10 decimal places per line:

# pi_digits.txt
3.1415926535 
  8979323846 
  2643383279
  ...


【Python】Basics - Inheritance

Inheritance

You don’t always have to start from scratch when writing a class. If the class you’re writing is a specialized version of another class you wrote, you can use inheritance. When one class inherits from another, it automatically takes on all the attributes and methods of the first class. The original class is called the parent class, and the new class is the child class. The child class inherits every attribute and method from its parent class but is also free to define new attributes and methods of its own.

class Car():
		"""A simple attempt to represent a car."""
		
		def init(self, make, model, year):
				"""Initialize attributes to describe a car.""" 
				self.make = make 
        self.model = model 						
				self.year = year

		def get_descriptive_name(self):
				"""Return a neatly formatted descriptive name.""" 
				long_name = str(self.year) + ' ' + self.make + ' ' + self.model 
				return long_name.title()

class ElectricCar(Car):
		"""Represent aspects of a car, specific to electric vehicles."""
		def __init__(self, make, model, year):
      	"""Initialize attributes of the parent class.""" 
        super().__init__(make, model, year)

my_tesla = ElectricCar('tesla', 'model s', 2016) 
print(my_tesla.get_descriptive_name()) # 2016 Tesla Model S
  ...


【Python】Basics - Modules

Function

Importing an Entire Module

To start importing functions, we first need to create a module. A module is a file ending in .py that contains the code you want to import into your program. Let’s make a module that contains the function make_pizza(). To make this module, we’ll remove everything from the file pizza.py except the function make_pizza():

# pizza.py
def make_pizza(size, *toppings):
		"""Summarize the pizza we are about to make.""" 
		print("\nMaking a " + str(size) + "-inch pizza with the following toppings:") 
		for topping in toppings:
			print("- " + topping)
  ...