美文网首页
python并发编程

python并发编程

作者: 红色火苗 | 来源:发表于2019-06-13 09:39 被阅读0次

一:多线程

#!/usr/bin/env python
# -*- coding: utf_8 -*-

# 1.多线程
from __future__ import print_function
import time
import threading
def say_hi():
    print('halo world')
def main():
    for i in range(5):
        thread = threading.Thread(target=say_hi)
        thread.start()
if __name__ == '__main__':
    stime = int(time.time())
    main()
    etime = int(time.time())

    print('use-time',etime-stime)

二:多线程的并发运行

#!/usr/bin/env python
# -*- coding: utf_8 -*-

# 2.多线程
from __future__ import print_function
import time
import threading
def say_hi():
    time.sleep(1)
    print('halo world')
def main():
    for i in range(5):
        thread = threading.Thread(target=say_hi)
        thread.start()

if __name__ == '__main__':
    stime = int(time.time())
    main()
    etime = int(time.time())
    print('use-time', etime - stime)

三:如何给线程传递参数?

#!/usr/bin/env python
# -*- coding: utf_8 -*-

# 3.多线程传递参数
from __future__ import print_function
import time
import threading
def say_hi(count,name):
    while count > 0:
        print(count,"hello",name)
        count -= 1

def main():
    usernames = ['jacke','bob','lucy','jone','mike']
    for i in range(5):
        thread = threading.Thread(target=say_hi,args=(50,usernames[i]))
        thread.start()

if __name__ == '__main__':
    stime = int(time.time())
    main()
    etime = int(time.time())
    print('use-time', etime - stime)

四:通过继承创建线程

from __future__ import  print_function

import threading

class MyThread (threading.Thread):
    def __init__(self,count,name):
        super(MyThread,self).__init__()
        self.count = count
        self.name  = name

    def run(self):
        while self.count > 0:
            print("hello",self.name)
            self.count -= 1

def main():
    usernames=['jacke','bob','lucy','joe','maike']
    for i in range(5):
        thread = MyThread(50,usernames[i])
        thread.start()

if __name__ == '__main__':
    main()

五:线程同步和互斥锁 保证线程的安全

# 5.线程同步和互斥锁
from __future__ import  print_function
import threading
lock = threading.Lock()
num = 0

def incre(count):
    global  num
    while count>0:
        with lock:
            num += 1
        count -= 1

def main():
    threads = []
    for i in range(10):
        thread = threading.Thread(target=incre,args=(100000,))
        thread.start()
        threads.append(thread)

    for thread in threads:
        thread.join()
    print("expected value is",num)

if __name__ == '__main__':
    main()

六:线程安全队列


# 先进先出 队列
from queue import Queue

q = Queue()

for i in range(10):
    q.put(i)

while not q.empty():
    print(q.get())

# 先进后出队列

from queue import LifoQueue

q = LifoQueue()

for i in range(10):
    q.put(i)

while not q.empty():
    print(q.get())


# 按指定优先级输出
from queue import PriorityQueue


class Job(object):
    def __init__(self, priority, description):
        self.priority = priority
        self.description = description
        print('New job:', description)
        return

    def __lt__(self, other):
        return self.priority < other.priority


q = PriorityQueue()

q.put(Job(5, 'Mid-level job'))
q.put(Job(10, 'Low-level job'))
q.put(Job(1, 'Important job'))

while not q.empty():
    next_job = q.get()
    print('Processing job', next_job.description)

未完待续:

多进程
协程

相关文章

  • 使用 Python 进行并发编程系列 - 收藏集 - 掘金

    使用 Python 进行并发编程 - asyncio 篇 (三) - 掘金 这是「使用Python进行并发编程...

  • Python并行编程(一):线程的基本概念和线程的两种定义方法以

    前言:本系列将包含Python并行编程的相关技术内容,包括Python线程、Python进程、并发编程的异步模式及...

  • Python并发编程

    协程 Python社区虽然对于异步编程的支持相比其他语言稍显迟缓,但是也在Python3.4中加入了asyncio...

  • Python 并发编程

    线程 线程调用的两种形式 1 . 直接调用 继承式调用 Thread实例的方法 同步锁 递归锁 递归锁,其中维护一...

  • python并发编程

    1. python 单进程 用下载两个文件模拟单进程的问题。 运行结果 2. python 多进程 多进程可以有效...

  • python并发编程

    一、引子 顾名思义,进程即正在执行的一个过程。进程是对正在运行程序的一个抽象。 进程的概念起源于操作系统,是操作系...

  • python并发编程

    一:多线程 二:多线程的并发运行 三:如何给线程传递参数? 四:通过继承创建线程 五:线程同步和互斥锁 保证线程的...

  • Python并发编程

    Python解释器由于设计时有GIL全局锁,导致了多线程无法利用多核。多线程的并发在Python中就是一个美丽的梦...

  • python并发编程

    基本概念 并行:多个任务同时执行,在同一时刻有多个任务在同时执行。 并发:多个任务分时交替执行,在同一时刻仅有1个...

  • Python 异步:完整教程

    Asyncio 允许我们在 Python 中使用基于协程的并发异步编程。尽管 asyncio 已经在 Python...

网友评论

      本文标题:python并发编程

      本文链接:https://www.haomeiwen.com/subject/wqodfctx.html