← Back to team overview

kicad-developers team mailing list archive

Re: KiCad Coroutines

 

On Thu, Jan 07, 2016 at 12:58:11PM +0100, jp charras wrote:
> However I am not sure it is "thread based".
> Threads are used to manage the stack using C++ language only.
> I am not sure they are used to manage coroutines themselves.

My fault, didn't read all the article.

Actually it only use the pthread to allocate a context (or more
correctly, the stack!) then use setjmp/longjmp as a switching primitive.
Then the thread dies... so in fact execution only remains in the main
thread (no GUI issues).

After that is the classic setjmp dispatcher without the tricks for
creating *correctly* the stack for the new context (embedded OSs usually
give you an helper function for that...), so it suffers from the same
issues. Be careful with local variables, registers are not preserved,
volatile declarations will abound :D

Also the pthread_attr_setstack seems quite esoteric, will need testing
to check its behaviour on Win32. If the function works as advertised
(i.e. the stack is correctly set) it would be the most portable thing I
could think of.

Another thing potentially problematic: if, as probably is, a pthread is
mapped to a Win32 thread, it takes a setjmp from a thread context (which
will die just after that) and then longjmp to it from *another* thread
(the main thread). That's potentially asking for trouble, depending on
what is in the saved context (which is an opaque array...).

Here (http://en.cppreference.com/w/c/program/longjmp) says:

    Jumping across threads (if the function that called setjmp was
    executed by another thread) is also undefined behavior.

'Undefined' is usually a bad thing (i.e. will break on the next
compiler/OS upgrade)...

Another thing I see is a probable portability flaw in the stack
allocation code, the man page says:

    The address specified in stackaddr should be suitably aligned: for
    full portability, align it on a page boundary
    (sysconf(_SC_PAGESIZE)). posix_memalign(3) may be useful for
    allocation. Probably, stacksize should also be a multiple of the
    system page size.

I would suppose a sane pthread implementation would align internally to
the correct size, but who knows!

So far this is the 'best' coroutine approach suggested, *if* it works
reliably on Win32. Another idea worth to check: is Pth available on Windows?

-- 
Lorenzo Marcantonio
CZ Srl - Parma

Attachment: signature.asc
Description: PGP signature


References