473,651 Members | 2,861 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

State Machines and Coroutines

State Machines and Coroutines

The other thread on goto: Lead me to want to ask... In the spirit of
state machines and coroutines, This n00b to C would like to know if
setjmp/longjmp are the only way to break out of a routine; leave the
function and re-enter the stack state.

I ask this because I've only briefly, as yet, reviewed these functions
and I believe longjmp will only return a designated int. Therefore I
would naively assume pointers would/could be used to return or alter
variables. I think I remember something mentioned about volatile
qualifiers being used as well.

Thank you,
Deiter
Jan 4 '06 #1
11 3416

Deiter wrote:
State Machines and Coroutines

The other thread on goto: Lead me to want to ask... In the spirit of
state machines and coroutines, This n00b to C would like to know if
setjmp/longjmp are the only way to break out of a routine; leave the
function and re-enter the stack state.

I ask this because I've only briefly, as yet, reviewed these functions
and I believe longjmp will only return a designated int. Therefore I
would naively assume pointers would/could be used to return or alter
variables. I think I remember something mentioned about volatile
qualifiers being used as well.


Hi Deiter,
I'm not entirely sure what you are trying to do here, but it sounds
like you want to exit a function before you have reached the end?

You can exit a function at any point with the return(var) statment. For
example if your fundtion returns an integer you can call return(0).

e.g.

int test_fnc(int input)
{
if (input >= 1)
return (1);
else
return(0);
}

After the return statment the function is removed from the stack.
Hope that helps,
Alastair

Jan 4 '06 #2
Alastair wrote:
Deiter wrote:
State Machines and Coroutines

The other thread on goto: Lead me to want to ask... In the spirit of
state machines and coroutines, This n00b to C would like to know if
setjmp/longjmp are the only way to break out of a routine; leave the
function and re-enter the stack state.

I ask this because I've only briefly, as yet, reviewed these functions
and I believe longjmp will only return a designated int. Therefore I
would naively assume pointers would/could be used to return or alter
variables. I think I remember something mentioned about volatile
qualifiers being used as well.

Hi Deiter,
I'm not entirely sure what you are trying to do here, but it sounds
like you want to exit a function before you have reached the end?

You can exit a function at any point with the return(var) statment. For
example if your fundtion returns an integer you can call return(0).

e.g.

int test_fnc(int input)
{
if (input >= 1)
return (1);
else
return(0);
}

After the return statment the function is removed from the stack.
Hope that helps,
Alastair


Hi, thanks Alastar but I'm a bit farther along than returns.

I believe setjmp allows you to "unwind" the stack to a prior position in
the routine when longjmp is then called.

But I'm generally interested in how the experienced in C consider
efficient state machines/coroutine structured programming.

Thanks
Jan 4 '06 #3
> Hi, thanks Alastar but I'm a bit farther along than returns.

I believe setjmp allows you to "unwind" the stack to a prior position in
the routine when longjmp is then called.

But I'm generally interested in how the experienced in C consider
efficient state machines/coroutine structured programming.

Thanks


Hi Dieter,

Hmm... nearly everything I do in C is as part of state mechines, but I
have not come across a need to use setjmp / longjmp, we need every bit
of efficiency that we can get (in some cases).

I'll be interested to hear what other poeple have to say...

Do you have a simple example of what you are trying to achieve?

Jan 4 '06 #4
Deiter wrote:

I think I remember something mentioned about volatile
qualifiers being used as well.


Hi,

One usual use of "volatile" is to inform the compiler that the variable
can be changed by some code not created by it. In other words, the
value can change "alone". Setjmp/longjmp man pages refers to this flag.

That means, in a code like:
int x;
x=8;
.... /* x is not changed */
printf("%d",x);

the compiler could optimize to:
int x;
.... /* x is not changed */
printf("%d",8);

The volatile flag prevents the compiler to do not made this kind of
optimization.

Probably some other users of this group can provide more information.

Kind regards.

PS: Sorry if this is something well known by you. About the other part
of your query, I'm not sure of understand it.

Jan 4 '06 #5
Alastair wrote:
Hi, thanks Alastar but I'm a bit farther along than returns.

I believe setjmp allows you to "unwind" the stack to a prior position in
the routine when longjmp is then called.

But I'm generally interested in how the experienced in C consider
efficient state machines/coroutine structured programming.

Thanks

Hi Dieter,

Hmm... nearly everything I do in C is as part of state mechines, but I
have not come across a need to use setjmp / longjmp, we need every bit
of efficiency that we can get (in some cases).

I'll be interested to hear what other poeple have to say...

Do you have a simple example of what you are trying to achieve?

I program in C for about 20 years, and I have yet to meet a case,
where I need to jump(or might want to).
And I hope I never have to learn how.
Before that time, I used fortran, and even there jump was mostly
to get the same result as continue and exit in C,so short,simple
forward jumps only ,to control loops,or to construct a case switch.
Jan 4 '06 #6

Deiter wrote:
State Machines and Coroutines

The other thread on goto: Lead me to want to ask... In the spirit of
state machines and coroutines, This n00b to C would like to know if
setjmp/longjmp are the only way to break out of a routine; leave the
function and re-enter the stack state.

I ask this because I've only briefly, as yet, reviewed these functions
and I believe longjmp will only return a designated int. Therefore I
would naively assume pointers would/could be used to return or alter
variables. I think I remember something mentioned about volatile
qualifiers being used as well.

Hi Deiter - read the topic (very recent) about using "Goto" - the
longjmp / setjmp are mentioned there with some comments later about
it's potencial use...

Alastair

Jan 4 '06 #7
Deiter wrote:

State Machines and Coroutines

The other thread on goto: Lead me to want to ask... In the
spirit of state machines and coroutines, This n00b to C would
like to know if setjmp/longjmp are the only way to break out of
a routine; leave the function and re-enter the stack state.

I ask this because I've only briefly, as yet, reviewed these
functions and I believe longjmp will only return a designated
int. Therefore I would naively assume pointers would/could be
used to return or alter variables. I think I remember something
mentioned about volatile qualifiers being used as well.


There is no such thing as a stack in C. There are only various
classes of storage (static, automatic, and allocated). A stack may
be used to implement automatic storage, but is not required.

After that the important thing to bear in mind is that after
executing a longjmp only volatile storage items are accessible.
From N869:

[#3] All accessible objects have values as of the time
longjmp was called, except that the values of objects of
automatic storage duration that are local to the function
containing the invocation of the corresponding setjmp macro
that do not have volatile-qualified type and have been
changed between the setjmp invocation and longjmp call are
indeterminate.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Jan 4 '06 #8
Deiter wrote:
State Machines and Coroutines

The other thread on goto: Lead me to want to ask... In the spirit of
state machines and coroutines, This n00b to C would like to know if
setjmp/longjmp are the only way to break out of a routine; leave the
function and re-enter the stack state.


Coroutines in C, by Simon Tatham:
http://www.chiark.greenend.org.uk/~s...oroutines.html

He uses a technique similar to the famous Duff's Device to implement
coroutines as described by Knuth.

There's also the Protothreads library, which uses the technique to
implement a form of cooperative multithreading.
http://www.sics.se/~adam/pt/pt-1.0-refman/main.html

Josh

Jan 4 '06 #9
In article <ou************ ********@comcas t.com>
Deiter <us**********@c omcast.net> wrote:
The other thread on goto: Lead me to want to ask... In the spirit of
state machines and coroutines, This n00b to C would like to know if
setjmp/longjmp are the only way to break out of a routine;
As others noted, the answer to this question as stated is "no",
because ordinary "return" breaks out of a routine, returning to
its caller. But the answer to the question I believe you intended
is "yes".
leave the function and re-enter the stack state.
Given this and the subject line ("coroutines "), it sounds as though
you wish to use longjmp() to resume execution in a function that
earlier used setjmp() to terminate its own execution, e.g.:

void f(void) {
... do some work ...
if (setjmp(label1) )
goto resume;
... do some more work ...
longjmp(label2, 1); /* "suspend" function f() */
resume:
... do yet more work ...
... ordinary function-return here ...
}

void g(void) {
... do some work ...
if (setjmp(label2) )
goto resume;
... do some more work ...
f(); /* f() will longjmp to label2 */
return;
label2:
/* we got here because f() executed a longjmp() */
... do more work ...
longjmp(label1, 1); /* go back into f() */
/* NOTREACHED */
}

This is not "legal" in Standard C, and some implementations --
including more than one that I wrote myself -- will abort your
program at the "longjmp(label1 , 1)" in g(), when they discover
that you are attempting to "reactivate " a stack frame that you
abandoned earlier (by executing the longjmp() in f()).

The key insight here is that longjmp() does not mean "suspend"; it
means "quit, and destroy all local variables". To implement
coroutines, you must *not* destroy the local variables. How this
can be done (and indeed, whether it is even possible) is
machine-dependent, and sometimes compiler-dependent. The longjmp
function is not guaranteed to do this, and does not work on real
implementations .
I ask this because I've only briefly, as yet, reviewed these functions
and I believe longjmp will only return a designated int.


This is correct; but the situation is considerably worse: longjmp()
may also destroy variables that are local to the function that used
setjmp(). To prevent this, such variables must be declared using
the "volatile" qualifier. In addition, the return value from setjmp()
cannot be stored in a variable! That is, the Standard renders the
effect of:

int x; /* or even "volatile int x" */
...
x = setjmp(jmpbuf);

undefined:

Environmental restriction

[#4] An invocation of the setjmp macro shall appear only in
one of the following contexts:

- the entire controlling expression of a selection or
iteration statement;

- one operand of a relational or equality operator with
the other operand an integer constant expression, with
the resulting expression being the entire controlling
expression of a selection or iteration statement;

- the operand of a unary ! operator with the resulting
expression being the entire controlling expression of a
selection or iteration statement; or

- the entire expression of an expression statement
(possibly cast to void).

[#5] If the invocation appears in any other context, the
behavior is undefined.

What this means is that to use longjmp(), the programmer must in
general implement his own stack of activations, e.g.:

struct Goto {
struct Goto *next;
volatile int longjmp_value1; /* can use volatile here */
volatile char *longjmp_value2 ; /* to avoid needing it below */
... etc ...
jmp_buf buf;
};
struct Goto *Goto_tos; /* current top of Goto stack */
...
void f(void) {
struct Goto g; /* need "volatile" if not in the struct */
...
g.next = Goto_tos; /* push ourselves on the stack */
Goto_tos = g;
if (setjmp(g.buf))
goto got_jumped_to;

... normal flow of control ...
return;
got_jumped_to:
Goto_tos = g.next; /* pop ourselves off the stack */
... the value(s) from longjmp are in g.longjmp_value N ...
... "gone-to" flow of control ...
}

void g(void) {
... normal flow of control ...
if (some exceptional condition) {
/* abort, ripping control away from all callers until top
of goto stack */
Goto_tos->longjmp_valu e1 = ...;
Goto_tos->longjmp_valu e2 = ...;
longjmp(Goto_to s->buf, 1);
}
... continue normal flow of control ...
}

Note that as soon as you start doing this, all functions involved
in the path between f() and g() that need to clean up (e.g., close
a file or free memory) start having to catch longjmp()s. In this
case, the "goto stack" structure provides the same thing Lisp
systems provide via "unwind-protect".
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Jan 4 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
2252
by: Timothy Fitz | last post by:
It seems to me that in python, generators are not truly coroutines. I do not understand why. What I see is that generators are used almost exclusively for generation of lists just-in-time. Side effects are frowned upon. Coroutines, in contrast, are like split functions where side effects are often as important or more important than return values. I am currently writing a real time strategy game where I have visual effects and use...
3
5063
by: Leonard J. Reder | last post by:
Hello list, I have been searching on the web for a while now for a specific Python implementation of an FSM. More specifically what I am looking for is a Python implementation of the so called UML Harel State Machine notion of a state machine. These are multi-threaded capable state machines with hierarchical representation capability (nested instances of state machines). They also have a unique conditional trigger symbol scheme for...
1
4308
by: Robert | last post by:
In Web.config file is a setting for sessionState. If I want to maintain a users' session state (ie use the Session object) in a web farm that is being load balanced by a Cisco CSS 11501 Switch. How do I setup sessionState so anything saved to the Session object stays with that session no matter what web server they get bounced around to?
4
4380
by: Shawnk | last post by:
This post is intended to verify that true value semantics DO NOT EXIST for the Enum class (relative to boolean operations). If this is true then (thus and therefore) you can not design state machines in C# where the machine can use the enumerated 'state' to execute (thus the term 'machine' as in 'state machine') the machine operations as this requires boolean operations to be performed on the state. .....
4
2090
by: libster | last post by:
Hello, I'm writing code and I have a scenario where I'm waiting to receive a msg and a timeout message at the same time. For example, I've set a timer so that if I don't receive a message in a certain time, then I will receive a timeout message. Based on which message I receive first I will perform certain tasks. Is there a good way to handle this in C++ without using statemachines. If
67
7352
by: Rui Maciel | last post by:
I've been delving into finite state machines and at this time it seems that the best way to implement them is through an intense use of the goto statement. Yet, everyone plus their granmother is constantly cursing at the goto statement, accusing it of being some sort of spawn of satan. So it seems we have a pickle here. The thing is, at first thought it seems that there aren't any viable alternatives which are better suited for this...
0
1187
by: Jean-Paul Calderone | last post by:
On Wed, 23 Apr 2008 07:17:46 -0700 (PDT), rocco.rossi@gmail.com wrote: They're not coroutines. The difference between generators in Python 2.4 and in Python 2.5 is that in Python 2.5, `yield´ can be used as part of an expression. If a generator is resumed via its `send´ method, then the `yield´ expression evaluates to the value passed to `send´. You still can't suspend execution through arbitrary stack frames; `yield´ only...
4
1262
by: ig | last post by:
First off, I'm a python n00b, so feel free to comment on anything if I'm doing it "the wrong way." I'm building a discrete event simulation tool. I wanted to use coroutines. However, I want to know if there's any way to hide a yield statement. I have a class that I'd like to look like this: class Pinger(Actor): def go(self): success = True
1
1325
by: Peter Morris | last post by:
Hi all I have a framework which runs on the full desktop .NET version which allows me to execute state machines. I'd like to move more logic over to the client, so I need something for Silverlight that some how lets me define state machines and execute them. Any recommendations? Thanks
0
8357
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8277
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8803
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8700
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8465
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6158
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5612
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
2701
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1588
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.