09-19-周五_14-48-32
This commit is contained in:
@@ -127,7 +127,7 @@ from greenlet import greenlet
|
||||
|
||||
def eat(name):
|
||||
print('%s eat 1' %name)
|
||||
g2.switch('aaron')
|
||||
g2.switch('张三')
|
||||
print('%s eat 2' %name)
|
||||
g2.switch()
|
||||
def play(name):
|
||||
@@ -138,7 +138,7 @@ def play(name):
|
||||
g1=greenlet(eat)
|
||||
g2=greenlet(play)
|
||||
|
||||
g1.switch('aaron') # 可以在第一次switch时传入参数,以后都不需要
|
||||
g1.switch('张三') # 可以在第一次switch时传入参数,以后都不需要
|
||||
```
|
||||
|
||||
单纯的切换(在没有io的情况下或者没有重复开辟内存空间的操作),反而会降低程序的执行速度
|
||||
@@ -224,8 +224,8 @@ def play(name):
|
||||
print('%s play 2' %name)
|
||||
|
||||
|
||||
g1=gevent.spawn(eat,'aaron')
|
||||
g2=gevent.spawn(play,name='aaron')
|
||||
g1=gevent.spawn(eat,'张三')
|
||||
g2=gevent.spawn(play,name='张三')
|
||||
g1.join()
|
||||
g2.join()
|
||||
#或者gevent.joinall([g1,g2])
|
||||
@@ -259,7 +259,7 @@ gevent.joinall([g1,g2])
|
||||
print('主')
|
||||
```
|
||||
|
||||
用threading.current_thread().getName()来查看每个g1和g2,查看的结果为DummyThread-n,即假线程
|
||||
用threading.current_thread().name来查看每个g1和g2,查看的结果为DummyThread-n,即假线程
|
||||
|
||||
```python
|
||||
from gevent import monkey;monkey.patch_all()
|
||||
@@ -267,13 +267,13 @@ import threading
|
||||
import gevent
|
||||
import time
|
||||
def eat():
|
||||
print(threading.current_thread().getName())
|
||||
print(threading.current_thread().name)
|
||||
print('eat food 1')
|
||||
time.sleep(2)
|
||||
print('eat food 2')
|
||||
|
||||
def play():
|
||||
print(threading.current_thread().getName())
|
||||
print(threading.current_thread().name)
|
||||
print('play 1')
|
||||
time.sleep(1)
|
||||
print('play 2')
|
||||
@@ -372,6 +372,8 @@ def talk(conn,addr):
|
||||
try:
|
||||
while True:
|
||||
res=conn.recv(1024)
|
||||
if len(res) == 0:
|
||||
continue
|
||||
print('client %s:%s msg: %s' %(addr[0],addr[1],res))
|
||||
conn.send(res.upper())
|
||||
except Exception as e:
|
||||
@@ -389,7 +391,7 @@ if __name__ == '__main__':
|
||||
from socket import *
|
||||
|
||||
client=socket(AF_INET,SOCK_STREAM)
|
||||
client.connect(('127.0.0.1',8080))
|
||||
client.connect(('127.0.0.1',8088))
|
||||
|
||||
|
||||
while True:
|
||||
@@ -414,7 +416,7 @@ def client(server_ip,port):
|
||||
|
||||
count=0
|
||||
while True:
|
||||
c.send(('%s say hello %s' %(threading.current_thread().getName(),count)).encode('utf-8'))
|
||||
c.send(('%s say hello %s' %(threading.current_thread().name,count)).encode('utf-8'))
|
||||
msg=c.recv(1024)
|
||||
print(msg.decode('utf-8'))
|
||||
count+=1
|
||||
|
Reference in New Issue
Block a user