Python3 多线程编程 (Thread Threading queue模块)

进程是资源的分配和调度的一个独立单元,而线程是CPU调度的基本单元。

 同一个进程中可以包括多个线程,并且线程共享整个进程的资源(寄存器、堆栈、上下文),一个进程至少包括一个线程。

Thread :

_thread.start_new_thread(target,args) 创建线程

import _thread
import time

def fun1():
    print("hello world %s \n" % time.ctime())

def main():
    _thread.start_new_thread(fun1,())
    _thread.start_new_thread(fun1,())
    time.sleep(2)
if __name__ == '__main__':
    main()

 

不用sleep可能会只使用一个线程。

Threading: threading 是比_thread 更高级的模块

import  threading
import time

def fun1(key):
    print("hello %s:%s"%(key,time.ctime()))

def main():
    thread=[]
    keys= ["zangsan","lisi","wangwu"]

    thread_count= len(keys)

    for i in range(thread_count):
        t= threading.Thread(target=fun1,args=(keys[i],))
        thread.append(t)
    for i in range(thread_count):
        thread[i].start() #启动线程

    for i in range(thread_count):
        thread[i].join() #阻塞主线程,等待子线程执行完后再执行后面的代码

if  __name__ == '__main__':
    main()

queue: 线程优先级队列。

Python 的 Queue 模块中提供了同步的、线程安全的队列类,包括FIFO(先入先出)队列Queue,LIFO(后入先出)队列LifoQueue,和优先级队列 PriorityQueue。

import threading
import queue

class test(threading.Thread):
    def __init__(self,q):
        threading.Thread.__init__(self)
        self._queue =q

    def run(self):
        while not self._queue.empty():
            ip=self._queue.get()
            print(ip)

def main():
    threads=[]
    threads_count =10
    q=queue.Queue()
    for i in range(1,255):
        q.put("183.170.26."+str(i))
    for i in range(threads_count):
        threads.append(test(q))
    for i in threads:
        i.start()
    for i in threads:
        i.join()
if __name__ == '__main__':
        main()

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值