Wednesday, March 31, 2010

A potted guide to stackless coroutines

Keen-eyed Asio users may have noticed that Boost 1.42 includes a new example, HTTP Server 4, that shows how to use stackless coroutines in conjunction with asynchronous operations. This follows on from the coroutines I explored in the previous three posts, but with a few improvements. In particular:

  • the pesky entry pseudo-keyword is gone; and
  • a new fork pseudo-keyword has been added.

The result bears a passing resemblance to C#'s yield and friends. This post aims to document my stackless coroutine API, but before launching into a long and wordy explanation, here's a little picture to liven things up:

[ Click image for full size. This image was generated from this source code using asioviz. ]

class coroutine

Every coroutine needs to store its current state somewhere. For that we have a class called coroutine:

class coroutine
{
public:
coroutine();
bool is_child() const;
bool is_parent() const;
bool is_complete() const;
};

Coroutines are copy-constructible and assignable, and the space overhead is a single int. They can be used as a base class:

class session : coroutine
{
...
};

or as a data member:

class session
{
...
coroutine coro_;
};

or even bound in as a function argument using bind() (see previous post). It doesn't really matter as long as you maintain a copy of the object for as long as you want to keep the coroutine alive.

reenter

The reenter macro is used to define the body of a coroutine. It takes a single argument: a pointer or reference to a coroutine object. For example, if the base class is a coroutine object you may write:

reenter (this)
{
... coroutine body ...
}

and if a data member or other variable you can write:

reenter (coro_)
{
... coroutine body ...
}

When reenter is executed at runtime, control jumps to the location of the last yield or fork.

The coroutine body may also be a single statement. This lets you save a few keystrokes by writing things like:

reenter (this) for (;;)
{
...
}

Limitation: The reenter macro is implemented using a switch. This means that you must take care when using local variables within the coroutine body. The local variable is not allowed in a position where reentering the coroutine could bypass the variable definition.

yield statement

This form of the yield keyword is often used with asynchronous operations:

yield socket_->async_read_some(buffer(*buffer_), *this);

This divides into four logical steps:

  1. yield saves the current state of the coroutine.
  2. The statement initiates the asynchronous operation.
  3. The resume point is defined immediately following the statement.
  4. Control is transferred to the end of the coroutine body.

When the asynchronous operation completes, the function object is invoked and reenter causes control to transfer to the resume point. It is important to remember to carry the coroutine state forward with the asynchronous operation. In the above snippet, the current class is a function object object with a coroutine object as base class or data member.

The statement may also be a compound statement, and this permits us to define local variables with limited scope:

yield
{
mutable_buffers_1 b = buffer(*buffer_);
socket_->async_read_some(b, *this);
}

yield return expression ;

This form of yield is often used in generators or coroutine-based parsers. For example, the function object:

struct interleave : coroutine
{
istream& is1;
istream& is2;
char operator()(char c)
{
reenter (this) for (;;)
{
yield return is1.get();
yield return is2.get();
}
}
};

defines a trivial coroutine that interleaves the characters from two input streams.

This type of yield divides into three logical steps:

  1. yield saves the current state of the coroutine.
  2. The resume point is defined immediately following the semicolon.
  3. The value of the expression is returned from the function.

yield ;

This form of yield is equivalent to the following steps:

  1. yield saves the current state of the coroutine.
  2. The resume point is defined immediately following the semicolon.
  3. Control is transferred to the end of the coroutine body.

This form might be applied when coroutines are used for cooperative threading and scheduling is explicitly managed. For example:

struct task : coroutine
{
...
void operator()()
{
reenter (this)
{
while (... not finished ...)
{
... do something ...
yield;
... do some more ...
yield;
}
}
}
...
};
...
task t1, t2;
for (;;)
{
t1();
t2();
}

yield break ;

The final form of yield is adopted from C# and is used to explicitly terminate the coroutine. This form is comprised of two steps:

  1. yield sets the coroutine state to indicate termination.
  2. Control is transferred to the end of the coroutine body.
Once terminated, calls to is_complete() return true and the coroutine cannot be reentered.

Note that a coroutine may also be implicitly terminated if the coroutine body is exited without a yield, e.g. by return, throw or by running to the end of the body.

fork statement ;

The fork pseudo-keyword is used when "forking" a coroutine, i.e. splitting it into two (or more) copies. One use of fork is in a server, where a new coroutine is created to handle each client connection:

reenter (this)
{
do
{
socket_.reset(new tcp::socket(io_service_));
yield acceptor->async_accept(*socket_, *this);
fork server(*this)();
} while (is_parent());
... client-specific handling follows ...
}

The logical steps involved in a fork are:

  1. fork saves the current state of the coroutine.
  2. The statement creates a copy of the coroutine and either executes it immediately or schedules it for later execution.
  3. The resume point is defined immediately following the semicolon.
  4. For the "parent", control immediately continues from the next line.

The functions is_parent() and is_child() can be used to differentiate between parent and child. You would use these functions to alter subsequent control flow.

Note that fork doesn't do the actual forking by itself. It is your responsibility to write the statement so that it creates a clone of the coroutine and calls it. The clone can be called immediately, as above, or scheduled for delayed execution using something like io_service::post().

299 comments:

«Oldest   ‹Older   201 – 299 of 299
mukoff said...

토토커뮤니티 The source, privy to the legal proceedings, said Shim asked the Seoul Eastern District Court, Monday, to nullify a two-month suspension by the Korea Skating Union (KSU), which was issued Dec. 21 last year.

totooff said...

토토사이트 However, even if the court approves Shim's application for the injunction, she will face yet another hurdle to qualify for the Olympics.

tototimez said...

메이저놀이터 The KSU will determine the final national team entries for the Feb. 4 to 20 Winter Games. Shim won the Olympic trials in May but was dropped from the national team in October, prior to the International Skating Union (ISU) World Cup season, after her text messages were leaked. She has not been competing or training with the rest of the team that has skated in World Cups, and the KSU may decide to leave her out of the Olympics, regardless of the court's decision.

mukclean said...

안전놀이터 Shim, a two-time Olympic relay gold medalist, chose not to appeal the ruling by the Korean Sport Olympic Committee last week, leading to speculation that she would take a different step to get herself reinstated.

scoretvs said...

보증업체 In a last-ditch effort to regain eligibility for the Beijing Winter Games, South Korean short track speed skating Olympic champion Shim Suk-hee has filed for a court injunction against a ban by the sport's national federation, a source said Thursday.

mtpolice said...

먹튀폴리스 Shim was suspended for making disparaging comments about her teammates and coaching staff during the 2018 PyeongChang Winter Olympics, the details of which were found in leaked text message exchanges with a coach.

sureman said...

슈어맨 The court plans to hold a hearing for both Shim and the KSU, Wednesday.

에볼루션룰렛 said...

Our vision is to maintain and strengthen our position as the world’s number one Live provider as gaming markets continue to evolve globally. Our culture is rooted in our corporate values:
kingkong112233
에볼루션룰렛

에볼루션카지노 said...

all the technical KINGDOM777 solutions and staff we need for 에볼루션-카지노 operators who provide world

Red Suit said...

Do you want to buy some jackets? Then come to our website. We have a large selection of fashionable and trendy jackets.

yahanvideonet said...

Awesome dispatch! I am indeed getting apt to over this info, is truly neighborly my buddy. Likewise fantastic blog here among many of the costly info you acquire. Reserve up the beneficial process you are doing here. Feel free to visit my website; 일본야동
일본야동
국산야동
일본야동
한국야동

koreayadongcom said...

This was an incredible post. Really loved studying your site post. Your data was very informative and helpful. I think you’ll proceed posting and updating frequently. Looking forward to your subsequent one. Feel free to visit my website; 일본야동
일본야동
국산야동
일본야동
한국야동

japanyadongcom said...


Keep up the good work , I read few blog posts on this website and I believe that your weblog is rattling interesting. Thank you for this effort, I will give you 5 stars for this. Kindly check the link below Thank you! Feel free to visit my website; 일본야동
일본야동
국산야동
일본야동
한국야동


Global Translation Help said...

Global Translation Help is a top translation company in USA whose team have professional language specialist whose team provide immigration translation services usa at the very lowest price.

토토사이트 said...

Saya membaca posting ini sepenuhnya tentang topik perbedaan teknologi terpanas dan sebelumnya, itu artikel yang luar biasa. 토토사이트

mukoff said...

메이저놀이터
She removed the video following a barrage of criticism, explaining later that a Chinese friend had given her the uniform and she wore it "for friendship."

totooff said...

토토사이트추천 "Athletes on the national team... should maintain our national dignity and honor," the premier told reporters.

tototimez said...

토토커뮤니티 She drew more ire during the Games when she said in an interview with Chinese media that she felt "at home" competing in Beijing.

mukclean said...

먹튀검증 The island's relations with Beijing have been especially frosty since President Tsai Ing-wen came to power in 2016, as she rejects the stance that the island is part of a single China.

scoretvs said...

보증업체 Self-ruled, democratic Taiwan is often held up as a bastion of liberalism but authorities have said Olympian Huang Yu-ting could be punished after she hit a nerve in January when she posted a clip of herself in the Chinese suit.

mtpolice said...

토토사이트 Taiwan reacted by calling on the International Olympic Committee to "prevent the interference of any political factors to suppress and belittle (Taiwan's) status."

sureman said...

안전놀이터 "Huang doesn't give a damn about Taiwan where she was born and raised ― she embraces China," lawmaker Chiu Chih-wei said on Facebook.

Alex Kim said...

Wonderful post.Thanks for sharing. You discuss the post very well A potted guide to stackless coroutines. If you are really looking for a professional translation company in Singapore then consult Singapore translators. Here, the well-experienced team of translators delivers you an exact translation that is free from any error.

Unknown said...

All You Need To Know About 현금바둑이게임 온라인현금바둑이 모바일바둑이

Unknown said...

GREATEST 메이저놀이터리스트 STRATEGY EVER

slotxo said...

แอพสล็อต ได้เงินจริง

unkhown said...

very good post, i certainly love this web site, keep on it 스마일도메인

data keluaran said...

Selamat mampir di web site yang bakal beri tambahan Info seputar permainan togel online, di mana area berkumpulnya para Situs togel online paling baik , bandar togel terpercaya dan bo togel terbesar yang sanggup menunjang seluruh taruhan bettor berlangsung lebih lancar dan safe selama tahun 2022 ini. Cukup dengan min bet 100 perak udah sanggup nikmati togel online dengan pasaran lengkap dan terpercaya di indonesia. Karena terhadap zaman yang udah moderen ini terlampau di perlukan untuk kami seluruh sebagai bettor ataupun master angka lebih pintar-pintar didalam melacak sebuah agen togel terpercaya. Data Sydney Dengan ada sebuah agen ataupun bandar online yang terpilih sebagai partner didalam dunia tebak angka atau lotto ( Lottre Gelap) ini pastinya kamu seluruh sanggup dengan safe untuk sanggup meraih pundi-pundi rupiah atau duit sampingan tiap tiap harinya.

Việt Hương Cosmetics said...

Dịch vụ gia công mỹ phẩm hiện đang được nhiều người tìm hiểu, bởi những lợi thế mà nó đem lại cho người đã có kinh nghiệm lâu năm trong việc kinh doanh như mức độ trung thành của khách hàng, giá thấp và có lợi nhuận cao hơn, chủ động toàn bộ vấn đề về hàng hoá, được nhà máy Việt Hương bảo hành đầy đủ chất lượng sản phẩm theo đúng hợp đồng. Công ty Việt Hương có hàng trăm công thức dộc quyền, dễ dàng giúp bạn mở rộng thương hiệu của mình tới nhiều đối tượng khách hàng khác nhau.

Anonymous said...

I am very happy to read a good article. Your website is also very good. I sincerely hope that I will be able to read your articles in the future.
goldfish356
에볼루션바카라

mike kke said...

It has fully emerged to crown Singapore's southern shores and undoubtedly placed her on the global map of residential landmarks.check my web site
메이저사이트

mike kke said...

It's amazing. I want to learn your writing skills. In fact, I also have a website. If you are okay, please visit once and leave your site info 먹튀검증커뮤니티

메이저사이트추천 said...

Traditional bookstores have always existed on high streets, but in the digital age, the internet is proving to become a serious competitor to traditional brick and mortar stores. This article examines both sides of the coin and provides an appropriate insight into the phenomenon of shopping of books online. 메이저사이트추천

Michael said...

เล่นบาคาร่าออนไลน์ SAGAME ฟรี 24 ชั่วโมง สมัครสมาชิกฟรี รับเครดิตฟรีทันทีตั้งแต่ครั้งแรกที่สมัครสมาชิก เชิญทางนี้ สมัครสมาชิกได้ที่เว็บไซต์ sagameherelao.com เราพร้อมให้บริการคุณด้วยใจจริง อยู่ที่ไหนก็สามารถเล่นบาคาร่ากับเราได้ รองรับการเข้าถึงทุกอุปกรณ์ ไม่ว่าจะเป็น โทรศัพท์มือถือ คอมพิวเตอร์ โน๊คบุ๊ค เพียงแค่คุณเข้าไปที่หน้าเว็บไซต์ของเราได้เลย ไม่ต้องโหลดอะไรเพิ่มเติม นอกจากนี้คุณยังได้มีสิทธิ์ลุ้นรับของรางวัลจากทางเว็บบาคาร่าของเราอย่างมากมาย รางวัลใหญ่คือ ทองคำมูลค่า 5 บาท แจกจริง ไม่จกตา

Laksana Karya Indonesia said...

thabk you for sharing such as informative article
best regards
jasa pengaspalan jakarta

Anonymous said...

I am very happy to see a good post. I look forward to posting useful information in the future. Thank you very much for your help. evolution
에볼루션카지노

안전놀이터 said...

Succeed! It could be one of the most useful blogs we have ever come across on the subject. Excellent info! I’m also an expert in this topic so I can understand your effort very well. Thanks for the huge help. 안전놀이터


Anonymous said...

nk you for the good information. I am also operating a website that provides good information. Please visit us later if you have time. evolution
에볼루션바카라

토토사이트 said...

토토사이트 Lewis Hamilton kept his nose stud in at the Monaco Grand Prix after motorsport's governing body extended the exemption on drivers wearing jewelry until the end of June.

토토커뮤니티 said...

토토커뮤니티 The FIA's exemption also covers Azerbaijan on June 12 and Canada on June 19. Discussions took place after the drivers' briefing at the Spanish GP, with a view to seeing how the wearing of jewelry could be enforced in a safe way.

파워볼사이트 said...

파워볼사이트 The FIA tightened its ban on non-regulatory underwear and body piercings with the rule part of official scrutineering, meaning such choices are subject to review by race officials.

카지노사이트 said...

카지노사이트 In preparation for this year's FIFA World Cup, South Korea will also face Brazil on June 2 in Seoul, Chile on June 6 in Daejeon, some 160 kilometers south of the capital, and Paraguay on June 10 in Suwon, 45 kilometers south of Seoul.

슬롯머신 said...

슬롯머신 South Korea had been close to scheduling a match against Argentina for June 14 but talks between the two sides fell through. The KFA then scrambled to find a new opponent and decided on the north African nation.

토토사이트 said...

토토사이트 The South Korea-Egypt showdown will feature the co-winners of the Premier League scoring title from this past season: Tottenham Hotspur's Son Heung-min for the home team, and Liverpool's Mohamed Salah for the visiting side.

Anonymous said...

o see a good post. I look forward to posting useful information in the future. Thank you very much for your help. evolution
에볼루션카지노

Anonymous said...

ce website. I also run a website. Mobile and PC versions are also operated as the best solution. Golden-evolution is very proud of you.
카지노사이트

Anonymous said...


crystaldiskinfo portable crack
peazip crack
winzip crack
winrar crack
valentina studio pro crack

Anonymous said...

n. I'm looking forward to good information. We share websites with each other.
에볼루션블랙잭

가자티비 said...

Whatever solution or combination of solutions the operator chooses, the Sports Broadcasting brand ensures the world's bst quality.
gazatv
가자티비

Anonymous said...

o, thank you for seeing the good posts, and I look forward to seeing more good posts in the future.
goldfish356
에볼루션룰렛

종티비 said...

There had been also various smawller sized winners in Massachusetts. Look at my homepage jongtv
종티비
스포츠 중계

토토사이트 said...

For the first time in his Tottenham Hotspur career, South Korean star Son Heung-min will represent his Premier League club on his home soil. And he wants to make the appearance a memorable one. 토토사이트

토토커뮤니티 said...

Though Wednesday's contest is an exhibition match, Son insisted he wants to kick off the preseason on the right note. 토토커뮤니티

메이저놀이터 said...

Football fans, hardcore or casual types alike, hang on Son's every word and every move, even in training. 메이저놀이터

슬롯커뮤니티 said...

Morimando had been pitching in for the CTBC Brothers in the Chinese Professional Baseball League in Taiwan this season, posting a 7-5 record and a 2.56 ERA in 15 appearances. 슬롯커뮤니티

토토사이트 said...

Throughout his Premier League career with Tottenham Hotspur that began in 2015, South Korean star Son Heung-min has been breaking records and setting milestones. 토토사이트

Anonymous said...

Best Game Evolution Introduction Golden Fish Solution, Hair Day, PC Access anywhere in the world
에볼루션소개

Bunny .cow said...

ทดลองเล่นบาคาร่าออนไลน์ SA GAME ได้แล้ววันนี้ ที่เว็บไซต์ sagameherelao.com เป็นระบบที่เว็บไซต์ของเราได้คิดค้นสร้างสรรค์ขึ้นมา เพื่อให้ตรงกับความต้องการของผู้เล่นมือใหม่ และข้อดีของระบบทดลองเล่นนั้นก็คือ เพื่อให้ผู้เล่นได้ฝึกฝนการเดิมพัน และเรียนรู้วิธีการเล่นบาคาร่า พร้อมทั้งทำความเข้าใจกับการวางแผนในการเดิมพัน สามารถเข้าสู่ระบบทดลองเล่นกับเว็บไซต์ของเราได้ตลอด 24 ชั่วโมง และสามารถเล่นผ่านโทรศัพท์สมาร์ทโฟนได้อย่างง่ายดาย รองรับทุกระบบปฏิบัติการ ทั้ง iOS และ Android

totosafeland said...

먹튀검증업체
It has fully emerged to crown Singapore's southern shores and undoubtedly placed her on the global map of residential landmarks. check my web site

totosafeland said...

Throughout his Premier League career with Tottenham Hotspur that began in 2015, South Korean star Son Heung-min has good 메이저놀이터

Unknown said...

She came to find too many issues, most notably what it is like to have an incredible helping nature to have other people completely comprehend a number of advanced things. You actually surpassed visitors’ expectations. Thanks for producing those great, safe, educational and in addition cool thoughts on the topic to Janet. 안전놀이터

Josefa Lale said...

Institutional Executive-Education.id is really a Jabodetabek individual teaching company that is definitely advised through encountered educators to all theme special areas of practice tutorials at all levels ... visit https://privat-inggris.netlify.app/kursus-bahasa-inggris-menteng.html for more details

사설 경마 사이트 said...

The most frequently asked questions are how can you win the horse race well? It is a word.사설 경마 사이트

Anonymous said...

흥미로운 블로그는 여기에 쓰여진 사실과 정보가 정확합니다. 블랙 가죽 오토바이 재킷 다낭 카지노

Erica Felver said...

Jabodetabek private tutoring services with teachers visiting the house. In excess of numerous active tutors you will need to teach various skills and lessons of the to adults ... visit https://privat-matematika.vercel.app/les-privat-matematika-jakarta-timur.html for further

Angel17 said...

What an excellent post. Thanks for sharing! https://www.appliancerepaircalg.ca/

Priceinall said...

Latest smartphone News, specs and price for visit priceinall.com

gostopsite com said...

My eyes are so hot that the place of love can't be, and I hear the treasure.

sportstotomen com said...

The ice that blooms is powerful. It is sending.

19guide03 com said...

A design like yours with a few simple adjustments would really make my blog shine.

casinosite zone said...

Please let me know where you got your design. Many thanks

sportstotozone com said...

Thanks for sharing this with so much of detailed information.

kellywade said...

Vespa scooters are renowned for their nimble handling and compact size, making them highly maneuverable in busy city streets. Their lightweight construction and agile design allow riders to navigate through traffic with ease, saving time and reducing commute frustrations.

gostopsite com said...

Great Post! I look forward to seeing more from you in the future.

sportstotomen com said...

There are some very great ideas above thank you!

19guide03 com said...

This is really helpful post and very informative there is no doubt about it.

casinosite zone said...

Everyone an extremely breathtaking chance to read from this blog.

sportstotozone com said...

Nice post. I learn something totally new and challenging on blogs.

leylandpartsbpauto said...

Looking for high-quality and affordable Spare Parts For Suzuki Alto? Look no further! Our extensive selection of Spare Parts for Suzuki Alto includes everything from brakes to suspension, ensuring that you can keep your vehicle in top shape. Order online today and get the parts you need for your Suzuki Alto at unbeatable prices!

safetotosite said...

I found some useful topics in this well detail form. Thanks. Good job you did it!

casinositenet said...

I am glad to discover this page. Thank you that I had a great read.

casinositekim said...

Thank you for your articles. I find them very helpful.

mttotosite said...

I like learning new stuff. So, thankyou for this information of yours.

Jasa Pancang said...

Nice post here, wish you all the best.
Best Regard.

zaamer said...

Fantastic article. Excellent reading material. I adore reading such lovely articles. Thanks!

snottor said...

I want to express my gratitude for the time and effort you put into making this fantastic post.

swaailen said...

Thank you, this is a subject close to my heart. Where are your contact information, though?

Jacki said...

Your commitment to providing accurate information is evident. Your blog is now my go-to source for reliable content. Keep up the fantastic work! Regards: digital marketing consultant

Jacki said...

Your writing style is captivating. I felt like I was on a journey as I read your post. Can't wait to see where your next piece takes us. Regards: rogan e balsan oil

keep bugs out of house said...

Your expertise and attention to detail is shining through your content, it's so inspiring. Also visit this link for more content keep bugs out of house

safetotosite said...

Terrific article! That is the type of information that are meant to be shared across the net.

casinositenet said...

I am continually browsing online for tips that can facilitate me. Thank you!

casinositekim said...

I am constantly thought about this, appreciate it for putting up.

mttotosite said...

Some truly nice stuff on this internet site, I like it.

sportstoto365 said...

Very good article. I certainly appreciate this website. Keep it up!

파워볼실시간 said...

What’s up to all, it’s genuinely a good for me to visit this website, it includes helpful Information.

토토사이트 추천 said...

Greate pieces. Keep writing such kind of info on your site. Im really impressed by your blog.

안전놀이터 said...

Quality content is the main to interest the viewers to pay a visit the website, that’s what this site is providing.

바카라사이트 추천 said...

Pretty! This has been an extremely wonderful post. Many thanks for providing this info.

«Oldest ‹Older   201 – 299 of 299   Newer› Newest»