Last active
August 13, 2021 09:08
-
-
Save CandyMi/bfcca99ba2dd3f93fc536cb900ba3b2b to your computer and use it in GitHub Desktop.
测试协程切换
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local cf = require "cf" | |
local cf_wait = cf.wait | |
local cf_wakeup = cf.wakeup | |
local co = cf.self() | |
local co1 = cf.fork(function() | |
while 1 do | |
cf_wait() | |
cf_wakeup(co) | |
end | |
end) | |
local co2 = cf.fork(function() | |
while 1 do | |
cf_wait() | |
cf_wakeup(co) | |
end | |
end) | |
-- 让出执行权. | |
cf.sleep(0) | |
local s = require"sys".now() | |
for i = 1, 300000 do | |
cf_wakeup(co1) | |
cf_wait() | |
cf_wakeup(co2) | |
cf_wait() | |
end | |
local e = require"sys".now() | |
print("耗时: ", e - s) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from greenlet import greenlet | |
def main(g1, g2): | |
while not g1.dead and not g2.dead : | |
if not g1.dead: | |
g1.switch(1) | |
if not g2.dead: | |
g2.switch(2) | |
print("main over.") | |
def func(num): | |
print(id(greenlet.getcurrent()), num) | |
g.switch() | |
print(id(greenlet.getcurrent()), num) | |
g = greenlet(main) | |
g1 = greenlet(func, g) | |
g2 = greenlet(func, g) | |
g.switch(g1, g2) | |
print("g.dead", g.dead) | |
print("g1.dead", g1.dead) | |
print("g2.dead", g2.dead) | |
''' | |
Result: | |
rppt@localhost:~/cfadmin$ python test_co.py | |
(139935641071696, 1) | |
(139935641071856, 2) | |
(139935641071696, 1) | |
(139935641071856, 2) | |
main over. | |
('g.dead', True) | |
('g1.dead', True) | |
('g2.dead', True) | |
root@localhost:~/cfadmin$ | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment