ct_return

The ct_return function returns control directly to the Cheap Threads scheduler via a call to longjmp(), bypassing the normal function return mechanism.

Prototype:

void ct_return( int rc );

Parameters:

rc
Return code; should be either CT_OKAY or CT_ERROR.

Return Value:

None (does not return if successful).

Discussion:

The ct_return function provides a way for a thread to return control to the scheduler without executing an ordinary return statement. The way it works is that the scheduler calls setjmp() just before invoking the thread. When the thread calls ct_return(), it calls longjmp() using the jmp_buf previously set up by the scheduler. The integer argument to ct_return() is treated the same as a return value, and should be either CT_OKAY or CT_ERROR.

There are at least two circumstances where ct_return() may be worth considering:

  • At the point where the thread decides to return control, it is buried in several layers of function calls.
  • The thread detects an unexpected error condition and needs to terminate immediately.
  • In either case, by using ct_return() you may be able to avoid a lot of tedious and error-prone checking of return codes. Depending on the circumstances, ct_return() may also reduce overhead by avoiding several layers of function returns.

    However, these benefits are not free. The scheduler's calls to setjmp() incur some overhead that would be wasted if you never call ct_return(). Consequently, ct_return() is disabled by default, so as not to impose overhead on applications that don't use it. If you want to use ct_return(), you must define the macro CT_RETURN when you compile the ctsched.c or ectsched.c module. Otherwise your code will compile but not link.

    Caveat:

    Because ct_return() is based on the setjmp/longjmp mechanism, it is hazardous to use in a C++ program. The problem is that longjmp() doesn't know about destructors. If there are any objects on the stack between the schduler's setjmp() and the thread's longjmp(), their destructors will not be called. The results may include, for example, leaks of memory or other resources. Whether this problem affects your application will depend on how the application works.

    Restrictions:

    An application may call ct_return() only from an active thread or user exit, i.e. when the scheduler is running. Otherwise ct_return() will issue an error message through ct_report_error() and put the Cheap Threads package into an error state, which you can clear only by calling ct_clear().
    Home