python】【Python基础】Python多线程如何实现

2020-12-01 11:42发布

10条回答
是你的小甜心呀
2楼 · 2020-12-01 14:33

1.当所有的线程都创建后再一起调用start()函数启动,而不是创建一个启动一个。构建一个线程类方法代码。

2.使用几种递归的运算的方法代码

3.使用Queue模块解决生产者和消费者问题方法代码


天天
3楼 · 2020-12-01 15:12

Python多线程编程中常用方法:

1、join()方法:如果一个线程或者在函数执行的过程中调用另一个线程,并且希望待其完成操作后才能执行,那么在调用线程的时就可以使用被调线程的join方法join([timeout]) timeout:可选参数,线程运行的最长时间

2、isAlive()方法:查看线程是否还在运行

3、getName()方法:获得线程名

4、setDaemon()方法:主线程退出时,需要子线程随主线程退出,则设置子线程的setDaemon()


@CcCc
4楼 · 2020-12-01 15:42

Python多线程编程中常用方法:

1、join()方法:如果一个线程或者在函数执行的过程中调用另一个线程,并且希望待其完成操作后才能执行,那么在调用线程的时就可以使用被调线程的join方法join([timeout]) timeout:可选参数,线程运行的最长时间

2、isAlive()方法:查看线程是否还在运行

3、getName()方法:获得线程名

4、setDaemon()方法:主线程退出时,需要子线程随主线程退出,则设置子线程的setDaemon()


小叮当
5楼 · 2020-12-01 16:46

创建函数并且传入Thread 对象中

t.py 脚本内容

import threading,time

from time import sleep, ctime

def now() :

    return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )

def test(nloop, nsec):

    print 'start loop', nloop, 'at:', now()

    sleep(nsec)

    print 'loop', nloop, 'done at:', now()

def main():

    print 'starting at:',now()

    threadpool=[]

    for i in xrange(10):

        th = threading.Thread(target= test,args= (i,2))

        threadpool.append(th)

    for th in threadpool:

        th.start()

    for th in threadpool :

        threading.Thread.join( th )

    print 'all Done at:', now()

if __name__ == '__main__':

        main()


风火轮
6楼 · 2020-12-01 17:05

Python多线程编程中常用方法:

1、join()方法:如果一个线程或者在函数执行的过程中调用另一个线程,并且希望待其完成操作后才能执行,那么在调用线程的时就可以使用被调线程的join方法join([timeout]) timeout:可选参数,线程运行的最长时间

2、isAlive()方法:查看线程是否还在运行

3、getName()方法:获得线程名

4、setDaemon()方法:主线程退出时,需要子线程随主线程退出,则设置子线程的setDaemon()



无需指教
7楼 · 2020-12-02 08:41

Python多线程编程中常用方法:

1、join()方法:如果一个线程或者在函数执行的过程中调用另一个线程,并且希望待其完成操作后才能执行,那么在调用线程的时就可以使用被调线程的join方法join([timeout]) timeout:可选参数,线程运行的最长时间

2、isAlive()方法:查看线程是否还在运行

3、getName()方法:获得线程名

4、setDaemon()方法:主线程退出时,需要子线程随主线程退出,则设置子线程的setDaemon()

Python线程同步:

(1)Thread的Lock和RLock实现简单的线程同步:

复制代码

复制代码

import threadingimport timeclass mythread(threading.Thread):    def __init__(self,threadname):
        threading.Thread.__init__(self,name=threadname)    def run(self):        global x
        lock.acquire()        for i in range(3):
            x = x+1
        time.sleep(1)        print x
        lock.release()if __name__ == '__main__':
    lock = threading.RLock()
    t1 = []    for i in range(10):
        t = mythread(str(i))
        t1.append(t)
    x = 0    for i in t1:
        i.start()

复制代码

复制代码

(2)使用条件变量保持线程同步:

复制代码

复制代码

# coding=utf-8import threadingclass Producer(threading.Thread):    def __init__(self,threadname):
        threading.Thread.__init__(self,name=threadname)    def run(self):        global x
        con.acquire()        if x == 10000:
            con.wait() 
            pass        else:            for i in range(10000):
                x = x+1
                con.notify()        print x
        con.release()class Consumer(threading.Thread):    def __init__(self,threadname):
        threading.Thread.__init__(self,name=threadname)    def run(self):        global x
        con.acquire()        if x == 0:
            con.wait()            pass        else:            for i in range(10000):
                x = x-1
            con.notify()        print x
        con.release()if __name__ == '__main__':
    con = threading.Condition()
    x = 0
    p = Producer('Producer')
    c = Consumer('Consumer')
    p.start()
    c.start()
    p.join()
    c.join()    print x

复制代码

复制代码

(3)使用队列保持线程同步:

复制代码

复制代码

# coding=utf-8import threadingimport Queueimport timeimport randomclass Producer(threading.Thread):    def __init__(self,threadname):
        threading.Thread.__init__(self,name=threadname)    def run(self):        global     queue
        i = random.randint(1,5)
        queue.put(i)        print self.getName(),' put %d to queue' %(i)
        time.sleep(1)class Consumer(threading.Thread):    def __init__(self,threadname):
        threading.Thread.__init__(self,name=threadname)    def run(self):        global     queue
        item = queue.get()        print self.getName(),' get %d from queue' %(item)
        time.sleep(1)if __name__ == '__main__':
    queue = Queue.Queue()
    plist = []
    clist = []    for i in range(3):
        p = Producer('Producer'+str(i))
        plist.append(p)    for j in range(3):
        c = Consumer('Consumer'+str(j))
        clist.append(c)    for pt in plist:
        pt.start()
        pt.join()    for ct in clist:
        ct.start()
        ct.join()

复制代码

复制代码

生产者消费者模式的另一种实现:

复制代码

复制代码

# coding=utf-8import timeimport threadingimport Queueclass Consumer(threading.Thread):    def __init__(self, queue):
        threading.Thread.__init__(self)
        self._queue = queue    def run(self):        while True:            # queue.get() blocks the current thread until an item is retrieved.
            msg = self._queue.get()            # Checks if the current message is the "quit"            if isinstance(msg, str) and msg == 'quit':                # if so, exists the loop                break            # "Processes" (or in our case, prints) the queue item            print "I'm a thread, and I received %s!!" % msg        # Always be friendly!        print 'Bye byes!'class Producer(threading.Thread):    def __init__(self, queue):
        threading.Thread.__init__(self)
        self._queue = queue    def run(self):        # variable to keep track of when we started
        start_time = time.time()        # While under 5 seconds..        while time.time() - start_time < 5:            # "Produce" a piece of work and stick it in the queue for the Consumer to process
            self._queue.put('something at %s' % time.time())            # Sleep a bit just to avoid an absurd number of messages
            time.sleep(1)        # This the "quit" message of killing a thread.
        self._queue.put('quit')if __name__ == '__main__':
    queue = Queue.Queue()
    consumer = Consumer(queue)
    consumer.start()
    producer1 = Producer(queue)
    producer1.start()

复制代码

复制代码

使用线程池(Thread pool)+同步队列(Queue)的实现方式:

复制代码

复制代码

# A more realistic thread pool example# coding=utf-8import time 
import threading 
import Queue 
import urllib2 

class Consumer(threading.Thread): 
    def __init__(self, queue):
        threading.Thread.__init__(self)
        self._queue = queue 
 
    def run(self):        while True: 
            content = self._queue.get() 
            if isinstance(content, str) and content == 'quit':                break
            response = urllib2.urlopen(content)        print 'Bye byes!' 
def Producer():
    urls = [        'http://www.python.org', 'http://www.yahoo.com'        'http://www.scala.org', 'http://cn.bing.com'        # etc.. 
    ]
    queue = Queue.Queue()
    worker_threads = build_worker_pool(queue, 4)
    start_time = time.time()    # Add the urls to process    for url in urls: 
        queue.put(url)  
    # Add the 'quit' message    for worker in worker_threads:
        queue.put('quit')    for worker in worker_threads:
        worker.join() 
    print 'Done! Time taken: {}'.format(time.time() - start_time) 
def build_worker_pool(queue, size):
    workers = []    for _ in range(size):
        worker = Consumer(queue)
        worker.start() 
        workers.append(worker)    return workers 
if __name__ == '__main__':
    Producer()

复制代码

复制代码

另一个使用线程池+Map的实现:

复制代码

import urllib2 
from multiprocessing.dummy import Pool as ThreadPool 
 
urls = [    'http://www.python.org', 
    'http://www.python.org/about/',    'http://www.python.org/doc/',    'http://www.python.org/download/',    'http://www.python.org/community/'
    ] 
# Make the Pool of workers
pool = ThreadPool(4) 
# Open the urls in their own threads# and return the results
results = pool.map(urllib2.urlopen, urls)#close the pool and wait for the work to finish 
pool.close() 
pool.join()


爱梦 - 拿来吧你
8楼 · 2020-12-02 09:51

线程是指进程内的一个执行单元,也是进程内的可调度实体.

与进程的区别:

(1) 地址空间:进程内的一个执行单元;进程至少有一个线程;它们共享进程的地址空间;而进程有自己独立的地址空间;

(2) 资源拥有:进程是资源分配和拥有的单位,同一个进程内的线程共享进程的资源

(3) 线程是处理器调度的基本单位,但进程不是.

(4) 二者均可并发执行.

简而言之,一个程序至少有一个进程,一个进程至少有一个线程.

线程的划分尺度小于进程,使得多线程程序的并发性高。

另外,进程在执行过程中拥有独立的内存单元,而多个线程共享内存,从而极大地提高了程序的运行效率。


赵小刀
9楼 · 2020-12-04 09:11

创建函数并且传bai入Thread 对象中

t.py 脚本内容

import threading,time

from time import sleep, ctime

def now() :

    return str( time.strftime( '%Y-%m-%d %H:%M:%S' , time.localtime() ) )

def test(nloop, nsec):

    print 'start loop', nloop, 'at:', now()

    sleep(nsec)

    print 'loop', nloop, 'done at:', now()

def main():

    print 'starting at:',now()

    threadpool=[]

    for i in xrange(10):

        th = threading.Thread(target= test,args= (i,2))

        threadpool.append(th)


相关问题推荐

  • 回答 1

    可以试下在cmd命令行执行,编辑器中对turtle的支持度不是很好。

  • 回答 6

    人工智能是一门起步晚却发展快速的科学。20 世纪以来科学工作者们不断寻求着赋予机器人类智慧的方法。现代人工智能这一概念是从英国科学家图灵的寻求智能机发展而来,直到1937年图灵发表的论文《理想自动机》给人工智能下了严格的数学定义,现实世界中实际要...

  • 回答 7

    代理ip网址http://www.goubanjia.com/http://www.ip181.com/https://www.kuaidaili.com/python 环境安装requests库安装bs4库proxies设置代理服务器地址proxies = {&#39;http&#39;:  &#39;http://61.155.164.110:3128&#39;}http://www.goub......

  • 回答 2

    要求:用户正确输入用户名和密码便成功登陆,分别有三次机会输入用户名和密码,超过3次便锁定分析:用两个while循环即可,代码如下:user_name = Brettpassword = 1314i = 0n = 0Is_exit = False  #进入循环标志while not Is_exit:User_name = input(please ...

  • 回答 2

    MacOS设置环境变量path的完全总结  一、MacOS加载bash shell 环境变量的加载顺序   mac 一般使用bash作为默认shell,Mac系统的环境变量,加载顺序为:1、系统级别的/etc/profile                                              ...

  • 回答 4

    当你运行代码的时候,需要你指定闹钟的时间,然后闹钟就会在指定的时间想起来。电脑pytho加载time模块,获取此时此刻的时间:import timet = time.localtime()print(t)时间是以字典的形式出现的。从字典里面提取时间信息:now = time.strftime(%H %M, t).spli...

  • 回答 5

    在几千条数据中有正负数,筛选出同一供应商下正负数相加为零的数据,正负数相加有可能为一正一负相加为零,也有可能是一正多负,也有可能一负多正,总体是将可以所有正负数相加为零的数据标注颜色出来。excel论坛上说计算量太 ...可以用pandas来处理...

  • 回答 2
    已采纳

    import sqlite3p = sqlite3.connect(file:memDB1?mode=memory&cache=shared, uri=True)p.execute('CREATE TABLE tbTest (fld1, fld2)')p.execute(INSERT INTO tbTest VALUES ('fld1', 'fld2'...

  • 回答 13

    Java企业级解决方案较多且成熟,国内搜索网站上对于各种问题的解答较多,相比而言,Python成熟企业级解决方案没Java多,资料多以外文为主。国内web开发大环境一直以Java为主,从业者人口基数众多,小白学习Java无论是书籍还是视频资料一搜一大把,从业者技术...

  • 回答 27

    当然可以了,不只是可以处理表格,而且是非常高效的额处理表格,能大大减轻工作量学会使用Python处理表格的话之前接了一个国企的case,说让我们给出一个解决方案关于数据处理方面的,去了他们天津的公司,一个部门7个人,7个人的工作我看了一下,我和我的同事...

  • 回答 22

    1、兼职处理数据2、兼职查询资料3、兼职P图

  • 回答 26

       Python是一门编程语言。相比于其他编程语言, Python爬取网页文档的接口更简洁;Python的urlib2包提供了完整的访问网页文档的API ;并且python中有优秀的第三方包可以高效实现网页抓取,可用极短的代码完成网页的标签过滤功能。所以Python被很多人称为爬虫。...

  • 回答 17

    可以的,python语法简单。刚开始学习可以试一下

  • 回答 25

    这两个其实现在用的都很普遍,java可能更好用一些吧

  • 回答 19

    1.if 语句1)基本用法:if 要判断的条件:    条件成立的时候,要做的事情else:    条件不成立的时候,要做的事情 if和else语句以及各自的缩进部分都是一个完整的代码块示例:2)if ,elifif 要判断的条件:    条件成立的时候,要做的事情elif 条件2...

  • 回答 26

    首先,从应用领域来看,Python语言涉及范围广,应用路径宽。其中包括:  (1)Web和Internet开发  (2)科学计算和统计  (3)人工智能  (4)桌面界面开发  (5)软件开发  (6)后端开发  (7)网络爬虫...

没有解决我的问题,去提问