Python学习——多线程学习

本文详细解释了进程和线程的概念及其区别,包括资源管理、地址空间、数据访问及线程间的通信等内容,并介绍了Python中创建和管理多线程的方法。

进程的概念:

An executing instance of a program is called a process.

Each process provides the resources needed to execute a program. A process has a virtual address space, executable code, open handles to system objects, a security context, a unique process identifier, environment variables, a priority class, minimum and maximum working set sizes, and at least one thread of execution. Each process is started with a single thread, often called the primary thread, but can create additional threads from any of its threads.

 

线程的概念:

A thread is an execution context, which is all the information a CPU needs to execute a stream of instructions.

Suppose you're reading a book, and you want to take a break right now, but you want to be able to come back and resume reading from the exact point where you stopped. One way to achieve that is by jotting down the page number, line number, and word number. So your execution context for reading a book is these 3 numbers.

If you have a roommate, and she's using the same technique, she can take the book while you're not using it, and resume reading from where she stopped. Then you can take it back, and resume it from where you were.

Threads work in the same way. A CPU is giving you the illusion that it's doing multiple computations at the same time. It does that by spending a bit of time on each computation. It can do that because it has an execution context for each computation. Just like you can share a book with your friend, many tasks can share a CPU.

On a more technical level, an execution context (therefore a thread) consists of the values of the CPU's registers.

Last: threads are different from processes. A thread is a context of execution, while a process is a bunch of resources associated with a computation. A process can have one or many threads.

Clarification: the resources associated with a process include memory pages (all the threads in a process have the same view of the memory), file descriptors (e.g., open sockets), and security credentials (e.g., the ID of the user who started the process).

进程和线程的区别:

程序并不能单独运行,只有将程序装载到内存中,系统为它分配资源才能运行,而这种执行的程序就称之为进程。程序和进程的区别就在于:程序是指令的集合,它是进程运行的静态描述文本;进程是程序的一次执行活动,属于动态概念。

  1. Threads share the address space of the process that created it; processes have their own address space.
  2. Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
  3. Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
  4. New threads are easily created; new processes require duplication of the parent process.
  5. Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.
  6. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process does not affect child processes.

 

 

多线程的调用:

两种形式:

直接调用:

import threading

t1 = threading.Thread(target=函数名,args=(参数1,)) #生成一个线程实例。
t1.start() #启动线程,必须用start()来启动。注意不是run
类调用:
class MyThread(threading.Thread):
    def __init__(self,num):
        super(MyThread,self).__init__()
        self.num = num
 
    def run(self):#这个动态属性名必须是run
 
        print("running on number:%s" %self.num)
 
        time.sleep(3)
 
if __name__ == '__main__':
 
    t1 = MyThread(1)   #直接建立实例即可。
    t2 = MyThread(2)
    t1.start()  #这个继承的类里面没有start的,但是还是可以使用,并且就是运行run。所以,注意了,继承的类里面必须是run哦。
    t2.start()

多线程的常见使用功能:

线程名.join()  这个就是等待,线程执行完成才能继续运行下面的代码

公共变量数据加锁,实现多线程操作数据的结果叠加(python3以后不会有这个问题):

Lock()

threading.Lock().acquire()    #启动锁,要在改动数据前

threading.Lock().release()   #释放锁

RLock(递归锁):

其他一样,但是这个可以启动多个锁。

信号量:threading.BoundedSemaphore(信号的数量int)  #启动的线程的数量 

使用方法和锁类似,把东西放在运行的函数里面即可。

参考网站:http://www.cnblogs.com/alex3714/articles/5230609.html

 

Event:

event.set() #就是表示设置了event.
event.isSet(): #检查event是否设立,已经设立,则为Ture.
event.wait()   #如果没有设置,则线程处于等待
event.clear()   #消除event,取消设置

队列queue:

作用:程序之间解耦;提高运行效率

class queue.Queue(maxsize=0) #先入先出
class queue.LifoQueue(maxsize=0) #last in fisrt out class queue.PriorityQueue(maxsize=0) #存储数据时可设置优先级的队列
Queue.qsize()
Queue.empty() #return True if empty  
Queue.full() # return True if full 
Queue.put(itemblock=Truetimeout=None)
Queue.put_nowait(item #不等待,直接回复错误结果,避免卡死
Queue.get(block=Truetimeout=None#等待的时间只有timeout 秒
Queue.get_nowait()

 

 

转载于:https://www.cnblogs.com/Ian-learning/p/8624219.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值