当前位置:首页 » 编程语言 » python并发

python并发

发布时间: 2022-01-08 16:43:14

python并发和java并发的区别

使用tornado的前提是你的服务是IO密集型的,并且你得写异步api,也可以请参考我签名中的框架,把tornado改造成eventloop+threadpool (GitHub - nikoloss/iceworld: tonado的multi-thread 多线程封装)。我们公司的android ios wap后台全是这套框架在提供服务。目前已经切换到一个分布式http响应群组里面了,此时tornado只是作为一个中继的gateway存在:GitHub - nikoloss/cellnest: 分布式service

在没有阻塞的情况下,python的性能肯定不如编译型语言。这种全异步的模型的优势也无法体现出来,一旦有IO操作了,这种全异步模型的第一步accpet新连接的操作并不会暂停,也就是只要有内容抵达,至少ioloop这个环节是可以照单全收的,接收之后协程处理,随着并发量增长它的性能下降是平稳且平滑的。反观线程模型,如果消费数据赶不上新连接新数据的生产,性能就会直线下降。

你的700qps差不多,你可以换3.1或者3.2的tornado试试,1100~1400应该可以跑出来。当然追求一个静态文本的输出性能是否有必要,我觉得实际情况比这种单纯的压测要复杂的多。

② 如何优雅的编写Python并发程序

在Python中,由于历史原因(GIL),使得Python中多线程的效果非常不理想.GIL使得任何时刻Python只能利用一个CPU核,并
且它的调度算法简单粗暴:多线程中,让每个线程运行一段时间t,然后强行挂起该线程,继而去运行其他线程,如此周而复始,直到所有线程结束.

这使得无法有效利用计算机系统中的"局部性",频繁的线程切换也对缓存不是很友好,造成资源的浪费.

据说Python官方曾经实现了一个去除GIL的Python解释器,但是其效果还不如有GIL的解释器,遂放弃.后来Python官方推出了"利
用多进程替代多线程"的方案,在Python3中也有concurrent.futures这样的包,让我们的程序编写可以做到"简单和性能兼得".

多进程/多线程+Queue

一般来说,在Python中编写并发程序的经验是:计算密集型任务使用多进程,IO密集型任务使用多进程或者多线程.另外,因为涉及到资源共享,所
以需要同步锁等一系列麻烦的步骤,代码编写不直观.另外一种好的思路是利用多进程/多线程+Queue的方法,可以避免加锁这样麻烦低效的方式.

现在在Python2中利用Queue+多进程的方法来处理一个IO密集型任务.

假设现在需要下载多个网页内容并进行解析,单进程的方式效率很低,所以使用多进程/多线程势在必行.

③ python多进程,多线程分别是并行还是并发

并发和并行

你吃饭吃到一半,电话来了,你一直到吃完了以后才去接,这就说明你不支持并发也不支持并行。
你吃饭吃到一半,电话来了,你停了下来接了电话,接完后继续吃饭,这说明你支持并发。
你吃饭吃到一半,电话来了,你一边打电话一边吃饭,这说明你支持并行。
并发的关键是你有处理多个任务的能力,不一定要同时。
并行的关键是你有同时处理多个任务的能力。
所以我认为它们最关键的点就是:是否是‘同时’。
Python 中没有真正的并行,只有并发
无论你的机器有多少个CPU, 同一时间只有一个Python解析器执行。这也和大部分解释型语言一致, 都不支持并行。这应该是python设计的先天缺陷。
javascript也是相同的道理, javascript早起的版本只支持单任务,后来通过worker来支持并发。
Python中的多线程
先复习一下进程和线程的概念
所谓进程,简单的说就是一段程序的动态执行过程,是系统进行资源分配和调度的一个基本单位。一个进程中又可以包含若干个独立的执行流,我们将这些执行流称为线程,线程是CPU调度和分配的基本单位。同一个进程的线程都有自己的专有寄存器,但内存等资源是共享的。
这里有一个更加形象的解释, 出自阮一峰大神的杰作:
http://www.ruanyifeng.com/blog/2013/04/processes_and_threads.html
Python中的thread的使用
通过 thread.start_new_thread 方法
import thread
import time

# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )

# Create two threads as follows
try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"

while 1:
pass

通过继承thread
#!/usr/bin/python
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
print_time(self.name, self.counter, 5)
print "Exiting " + self.name

def print_time(threadName, delay, counter):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1

# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads
thread1.start()
thread2.start()
print "Exiting Main Thread"

线程的同步
#!/usr/bin/python

import threading
import time

class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
# Get lock to synchronize threads
threadLock.acquire()
print_time(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()

def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1

threadLock = threading.Lock()
threads = []

# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)

# Start new Threads
thread1.start()
thread2.start()

# Add threads to thread list
threads.append(thread1)
threads.append(thread2)

# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"

利用multiprocessing多进程实现并行
进程的创建
Python 中有一套类似多线程API 的的类来进行多进程开发: multiprocessing
这里是一个来自官方文档的例子:
from multiprocessing import Process
def f(name):
print 'hello', name

if __name__ == '__main__':
p = Process(target=f, args=('bob',))
p.start()
p.join()

类似与线程,一可以通过继承process类来实现:
from multiprocessing import Process
class Worker(Process):
def run(self):
print("in" + self.name)

if __name__ == '__main__':
jobs = []
for i in range(5):
p = Worker()
jobs.append(p)
p.start()
for j in jobs:
j.join()

进程的通信
Pipe()
pipe()函数返回一对由双向通信的管道连接的对象,这两个对象通过send, recv 方法实现 信息的传递
from multiprocessing import Process, Pipe

def f(conn):
conn.send([42, None, 'hello'])
conn.close()

if __name__ == '__main__':
parent_conn, child_conn = Pipe()
p = Process(target=f, args=(child_conn,))
p.start()
print parent_conn.recv() # prints "[42, None, 'hello']"
p.join()

Quene
from multiprocessing import Process, Queue
def f(q):
q.put([42, None, 'hello'])

if __name__ == '__main__':
q = Queue()
p = Process(target=f, args=(q,))
p.start()
print q.get() # prints "[42, None, 'hello']"
p.join()

进程间的同步
Python 中多进程中也有类似线程锁的概念,使用方式几乎一样:
from multiprocessing import Process, Lock
def f(l, i):
l.acquire()
print 'hello world', i
l.release()
if __name__ == '__main__':
lock = Lock()
for num in range(10):
Process(target=f, args=(lock, num)).start()

进程间的共享内存
每个进程都有独自的内存,是不能相互访问的, 也行 python官方觉得通过进程通信的方式过于麻烦,提出了共享内存的概念,以下是官方给出的例子:
from multiprocessing import Process, Value, Array

def f(n, a):
n.value = 3.1415927
for i in range(len(a)):
a[i] = -a[i]

if __name__ == '__main__':
num = Value('d', 0.0)
arr = Array('i', range(10))

p = Process(target=f, args=(num, arr))
p.start()
p.join()

print num.value
print arr[:]

总结
python通过多进程实现多并行,充分利用多处理器,弥补了语言层面不支持多并行的缺点。Python, Node.js等解释型语言似乎都是通过这种方式来解决同一个时间,一个解释器只能处理一段程序的问题, 十分巧妙。

④ python简单的并发问题

  • #!/usr/bin/envpython#-*-coding:utf-8-*-#author:ChanghuaGongimporttime,threading#fromurllib.requestimportRequest,urlopenpy3#fromurllib.#URLreq=urllib2.Request('http://47.93.169.69:10080/pigeon-web/user/user

  • #!/usr/bin/env python

    # -*- coding:utf-8 -*-

    # author: Changhua Gong

    import time,threading

    # from urllib.request import Request, urlopen py3

    # from urllib.error import URLError py3

    import urllib2

    #URL

    req = urllib2.Request('http://47.93.169.69:10080/pigeon-web/user/userExtraInfo?userId=1')

    #

    rule = {0:500,1:30}

    '''

    Rule规则:0:50,第一次运行不睡眠即为0,直接并发50次;1:20,第二秒,相当于睡眠1秒,然后并发20次,

    如第三秒需并发500次,则rule = {0:50,1:20,1:500}

    '''

    #Open url

    def geturl():

    time_b = time.time()

    try:

    response = urllib2.urlopen(req)

    print(response.read().decode("utf-8")) # 打印输出内容

    except urllib2.URLError as e:

    if hasattr(e, 'reason'):

    print('We failed to reach a server.')

    print('Reason: ', e.reason)

    elif hasattr(e, 'code'):

    print('The server couldn/'t fulfill the request.')

    print('Error code: ', e.code)

    time_e = time.time()

    print("Thread %s runned for %ss" % (threading.current_thread().name, (time_e - time_b))) #线程访问时效

    if __name__=='__main__':

    for k in rule:

    time.sleep(k)

    for i in range(rule[k]):

    t = threading.Thread(target=geturl)

    t.start()

⑤ Python有哪些并发方案

协程。
python的爬虫scrapy就是采用了协程。
具体看《流程的python》第十六章。

⑥ 如何使用Python实现并发编程

多线程几乎是每一个程序猿在使用每一种语言时都会首先想到用于解决并发的工具(JS程序员请回避),使用多线程可以有效的利用CPU资源(Python例外)。然而多线程所带来的程序的复杂度也不可避免,尤其是对竞争资源的同步问题。

然而在python中由于使用了全局解释锁(GIL)的原因,代码并不能同时在多核上并发的运行,也就是说,Python的多线程不能并发,很多人会发现使用多线程来改进自己的Python代码后,程序的运行效率却下降了,这是多么蛋疼的一件事呀!如果想了解更多细节,推荐阅读这篇文章。实际上使用多线程的编程模型是很困难的,程序员很容易犯错,这并不是程序员的错误,因为并行思维是反人类的,我们大多数人的思维是串行(精神分裂不讨论),而且冯诺依曼设计的计算机架构也是以顺序执行为基础的。所以如果你总是不能把你的多线程程序搞定,恭喜你,你是个思维正常的程序猿:)

Python提供两组线程的接口,一组是thread模块,提供基础的,低等级(Low Level)接口,使用Function作为线程的运行体。还有一组是threading模块,提供更容易使用的基于对象的接口(类似于Java),可以继承Thread对象来实现线程,还提供了其它一些线程相关的对象,例如Timer,Lock

使用thread模块的例子
import thread

def worker():
"""thread worker function"""
print 'Worker'
thread.start_new_thread(worker)
使用threading模块的例子
import threading
def worker():
"""thread worker function"""
print 'Worker'
t = threading.Thread(target=worker)
t.start()
或者Java Style
import threading

class worker(threading.Thread):
def __init__(self):
pass
def run():
"""thread worker function"""
print 'Worker'

t = worker()
t.start()

⑦ 并发和并行的区别 python

并发:就是同时做多件事情。

例如:终端用户程序利用并发功能,在输入数据的同时响应用户输入。服务器利用并发,在处理第一个请求的同时响应第二个请求。只要你希望程序同时做多件事情,就需要并发。

很多人看到“并发”就会想到“多线程”,其实他们是有区别的。多线程只是并发的一种形式,但不是唯一形式


并行:就是把正在执行的大量任务分割成小块,分配给多个同时运行的线程。

一般情况下,为了让CPU充分利用,并行处理都会采用多线程。


所以说:并行处理是多线程的一种,而多线程是并发的一种。


还有一种非常重要但很多人不熟悉的并发类型:异步编程,它也是并发的一种形式。

⑧ python gevent 能解决并发状态吗

1. gevent.server.StreamServer 会针对每个客户端连接启动一个greenlet处理,要注意的是,如果不循环监听( 阻塞在read ),

每个greenlet会在完成后立即退出,从而导致客户端退出( 发送FIN_ACK给客户端 )。这个问题折腾了一晚上,终于弄明白了。坑爹啊。。。

2. 要非常仔细的检查,greenlet处理的代码,发现有可能阻塞IO的地方,尽量用gevent提供的库。

3. 一些第三方库隐藏了自己的实现( 通常是直接封装C库),要使得gevent兼容它们,可以用monkey_patch,但不保证全部管用。

4. 最后最后的一点,gevent的greenlet性能非常高,所以如果是用它作为并发的client端,那么一定要注意,你的server端处理速度一定要足够快!
否则你的客户端代码会因为服务端的慢速,而失去了greenlet的优势。

⑨ 如何在Python中编写并发程序

GIL

在Python中,由于历史原因(GIL),使得Python中多线程的效果非常不理想.GIL使得任何时刻Python只能利用一个CPU核,并
且它的调度算法简单粗暴:多线程中,让每个线程运行一段时间t,然后强行挂起该线程,继而去运行其他线程,如此周而复始,直到所有线程结束.

这使得无法有效利用计算机系统中的"局部性",频繁的线程切换也对缓存不是很友好,造成资源的浪费.

据说Python官方曾经实现了一个去除GIL的Python解释器,但是其效果还不如有GIL的解释器,遂放弃.后来Python官方推出了"利
用多进程替代多线程"的方案,在Python3中也有concurrent.futures这样的包,让我们的程序编写可以做到"简单和性能兼得".

多进程/多线程+Queue

一般来说,在Python中编写并发程序的经验是:计算密集型任务使用多进程,IO密集型任务使用多进程或者多线程.另外,因为涉及到资源共享,所
以需要同步锁等一系列麻烦的步骤,代码编写不直观.另外一种好的思路是利用多进程/多线程+Queue的方法,可以避免加锁这样麻烦低效的方式.

现在在Python2中利用Queue+多进程的方法来处理一个IO密集型任务.

假设现在需要下载多个网页内容并进行解析,单进程的方式效率很低,所以使用多进程/多线程势在必行.
我们可以先初始化一个tasks队列,里面将要存储的是一系列dest_url,同时开启4个进程向tasks中取任务然后执行,处理结果存储在一个results队列中,最后对results中的结果进行解析.最后关闭两个队列.

下面是一些主要的逻辑代码.

# -*- coding:utf-8 -*-

#IO密集型任务
#多个进程同时下载多个网页
#利用Queue+多进程
#由于是IO密集型,所以同样可以利用threading模块

import multiprocessing

def main():
tasks = multiprocessing.JoinableQueue()
results = multiprocessing.Queue()
cpu_count = multiprocessing.cpu_count() #进程数目==CPU核数目

create_process(tasks, results, cpu_count) #主进程马上创建一系列进程,但是由于阻塞队列tasks开始为空,副进程全部被阻塞
add_tasks(tasks) #开始往tasks中添加任务
parse(tasks, results) #最后主进程等待其他线程处理完成结果

def create_process(tasks, results, cpu_count):
for _ in range(cpu_count):
p = multiprocessing.Process(target=_worker, args=(tasks, results)) #根据_worker创建对应的进程
p.daemon = True #让所有进程可以随主进程结束而结束
p.start() #启动

def _worker(tasks, results):
while True: #因为前面所有线程都设置了daemon=True,故不会无限循环
try:
task = tasks.get() #如果tasks中没有任务,则阻塞
result = _download(task)
results.put(result) #some exceptions do not handled
finally:
tasks.task_done()

def add_tasks(tasks):
for url in get_urls(): #get_urls() return a urls_list
tasks.put(url)

def parse(tasks, results):
try:
tasks.join()
except KeyboardInterrupt as err:
print "Tasks has been stopped!"
print err

while not results.empty():
_parse(results)

if __name__ == '__main__':
main()

利用Python3中的concurrent.futures包

在Python3中可以利用concurrent.futures包,编写更加简单易用的多线程/多进程代码.其使用感觉和Java的concurrent框架很相似(借鉴?)
比如下面的简单代码示例

def handler():
futures = set()

with concurrent.futures.ProcessPoolExecutor(max_workers=cpu_count) as executor:
for task in get_task(tasks):
future = executor.submit(task)
futures.add(future)

def wait_for(futures):
try:
for future in concurrent.futures.as_completed(futures):
err = futures.exception()
if not err:
result = future.result()
else:
raise err
except KeyboardInterrupt as e:
for future in futures:
future.cancel()
print "Task has been canceled!"
print e
return result

总结

要是一些大型Python项目也这般编写,那么效率也太低了.在Python中有许多已有的框架使用,使用它们起来更加高效.

⑩ python 多进程是真的并发吗

Python提供了非常好用的多进程包multiprocessing,你只需要定义一个函数,Python会替你完成其他所有事情。
借助这个包,可以轻松完成从单进程到并发执行的转换。

1、新建单一进程
如果我们新建少量进程,可以如下:
import multiprocessing
import time

def func(msg):
for i in xrange(3):
print msg
time.sleep(1)

if __name__ == "__main__":
p = multiprocessing.Process(target=func, args=("hello", ))
p.start()
p.join()
print "Sub-process done."12345678910111213

2、使用进程池
是的,你没有看错,不是线程池。它可以让你跑满多核CPU,而且使用方法非常简单。
注意要用apply_async,如果落下async,就变成阻塞版本了。
processes=4是最多并发进程数量。
import multiprocessing
import time

def func(msg):
for i in xrange(3):
print msg
time.sleep(1)

if __name__ == "__main__":
pool = multiprocessing.Pool(processes=4)
for i in xrange(10):
msg = "hello %d" %(i)
pool.apply_async(func, (msg, ))
pool.close()
pool.join()
print "Sub-process(es) done."12345678910111213141516

3、使用Pool,并需要关注结果
更多的时候,我们不仅需要多进程执行,还需要关注每个进程的执行结果,如下:
import multiprocessing
import time

def func(msg):
for i in xrange(3):
print msg
time.sleep(1)
return "done " + msg

if __name__ == "__main__":
pool = multiprocessing.Pool(processes=4)
result = []
for i in xrange(10):
msg = "hello %d" %(i)
result.append(pool.apply_async(func, (msg, )))
pool.close()
pool.join()
for res in result:
print res.get()
print "Sub-process(es) done."

2014.12.25更新
根据网友评论中的反馈,在Windows下运行有可能崩溃(开启了一大堆新窗口、进程),可以通过如下调用来解决:
multiprocessing.freeze_support()1

附录(自己的脚本):
#!/usr/bin/python
import threading
import subprocess
import datetime
import multiprocessing

def dd_test(round, th):
test_file_arg = 'of=/zbkc/test_mds_crash/1m_%s_%s_{}' %(round, th)
command = "seq 100 | xargs -i dd if=/dev/zero %s bs=1M count=1" %test_file_arg
print command
subprocess.call(command,shell=True,stdout=open('/dev/null','w'),stderr=subprocess.STDOUT)

def mds_stat(round):
p = subprocess.Popen("zbkc mds stat", shell = True, stdout = subprocess.PIPE)
out = p.stdout.readlines()
if out[0].find('active') != -1:
command = "echo '0205pm %s round mds status OK, %s' >> /round_record" %(round, datetime.datetime.now())
command_2 = "time (ls /zbkc/test_mds_crash/) 2>>/round_record"
command_3 = "ls /zbkc/test_mds_crash | wc -l >> /round_record"
subprocess.call(command,shell=True)
subprocess.call(command_2,shell=True)
subprocess.call(command_3,shell=True)
return 1
else:
command = "echo '0205 %s round mds status abnormal, %s, %s' >> /round_record" %(round, out[0], datetime.datetime.now())
subprocess.call(command,shell=True)
return 0

#threads = []
for round in range(1, 1600):
pool = multiprocessing.Pool(processes = 10) #使用进程池
for th in range(10):
# th_name = "thread-" + str(th)
# threads.append(th_name) #添加线程到线程列表
# threading.Thread(target = dd_test, args = (round, th), name = th_name).start() #创建多线程任务
pool.apply_async(dd_test, (round, th))
pool.close()
pool.join()
#等待线程完成
# for t in threads:
# t.join()

if mds_stat(round) == 0:
subprocess.call("zbkc -s",shell=True)
break

热点内容
访问拦截怎么解除安卓 发布:2024-09-20 17:28:48 浏览:275
萝卜干存储 发布:2024-09-20 17:21:37 浏览:715
苹果手机如何迁移软件到安卓手机 发布:2024-09-20 17:21:34 浏览:692
查看服务器ip限制 发布:2024-09-20 16:56:27 浏览:389
p搜系统只缓存1页为什么 发布:2024-09-20 16:48:51 浏览:839
上网的账号和密码是什么东西 发布:2024-09-20 16:31:31 浏览:612
安卓手机王者荣耀如何调超高视距 发布:2024-09-20 16:31:30 浏览:428
安卓G是什么app 发布:2024-09-20 16:23:09 浏览:81
iphone怎么压缩文件 发布:2024-09-20 16:08:18 浏览:356
linux查看用户名密码是什么 发布:2024-09-20 16:03:20 浏览:744