python的GIL

In CPython, the global interpreter lock, or GIL, is a mutex that prevents multiple native threads from executing Python bytecodes at once. This lock is necessary mainly because CPython’s memory management is not thread-safe. (However, since the GIL exists, other features have grown to depend on the guarantees that it enforces.)

上面的核心意思就是,无论你启多少个线程,你有多少个cpu, Python在执行的时候会淡定的在同一时刻只允许一个线程运行

线程

1同步锁

2死锁递归锁

3:信号量和同步对象(了解)

4队列------生产者消费者模型

5进程

 

线程的基本调用

 

<python的线程与threading模块>

import threading  # 线程
import time


def Hi(num):
    print('hello %d' % num)
    time.sleep(3)

if __name__ == '__main__':
    # 第一个参数是要执行的函数名,第二个是函数的参数(必须是可迭代对象)
    t1 = threading.Thread(target=Hi, args=(10, ))  # 创建一个线程对象
    t1.start()  # 开启线程
    t2 = threading.Thread(target=Hi, args=(9, ))  # 创建一个线程对象
    t2.start()  # 开启线程
    print('ending....')
#   这就是并发的现象

#   并行:指的是两个或者多个事件在同一时刻发生(同时调用多核)
#   并发:指的是两个或者多个事件在同一时间间隔内发生(在一个核内快速的切换)

第二种调用方式

import threading
import time


class MyThread(threading.Thread):
    def __init__(self,num):
        threading.Thread.__init__(self)
        self.num = num

    def run(self):#定义每个线程要运行的函数

        print("running on number:%s" %self.num)

        time.sleep(3)

if __name__ == '__main__':

    t1 = MyThread(1)
    t2 = MyThread(2)
    t1.start()
    t2.start()
    
    print("ending......")

join和setDaemon

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 18-5-22 下午8:45
# @Author  : LK
# @File    : lesson2.py
# @Software: PyCharm

import threading
import time

def music():
    print('begin listen music %s'%time.ctime())
    # t = input('请输入内容>>>')
    # time.sleep(3)
    print('stop listen music %s'%time.ctime())
    # print(t)


def game():
    print('begin to game %s'%time.ctime())
    time.sleep(5)
    print('stop to game %s'%time.ctime())

if __name__ == '__main__':
    t1 = threading.Thread(target=music)
    t2 = threading.Thread(target=game)

    t1.start()
    t2.start()

    # t1.join()   #   join就是等待的意思,让该线程执行完毕后,在执行主线程
    # t2.join()   # 注意如果注释这一句,结果是什么

    print('ending....')

    print(t1.getName())  #  获取线程名,
join

相关文章: