3

I'm porting a software from an embedded computer to a Linux machine. (Ubuntu 14.04 or Raspbian (raspberry pi))

The original program was using setjmp/longjmp to handle timeout and CTRL+C event. It was running on a Microcontroller with a single main (one thread).

I'm trying to have a similar behaviour while using threads (pthreads).

The idea is that I want either a timeout or a CTRL+C to restart an infinite loop.

The original code was doing something like the code below. I don't mind to drop the setjmp/longjmp by something else. (ex: try/catch or signal or pthread_kill, conditional variable, etc..)

Any idea how to implement similar behavior with C/C++ ?

Here is the code which seems to partially work and is probably not recommended/broken:

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <setjmp.h>

// Define
#define TICK_NS_TIME (10000000)                                                 // 0.01 sec = 10 ms (100 times per second)
#define NS_PER_SEC   (1000000000)                                               // Nano sec per second.
#define TICK_PER_SEC (NS_PER_SEC/TICK_NS_TIME)                                  // Number of tick per second (Ex:100)
#define TIMEOUT_COUNT (30*TICK_PER_SEC)                                         // 30 seconds timeout (with 100 tick per second)

// Env set/long jmp
#define ENV_SZ (2)
#define ENV_TIMEOUT (0)
#define ENV_CTRLC (1)
static jmp_buf env[ENV_SZ];

// Variables
int timeout_val;


// sig handler.
void signal_handler(int signo)
{
    pthread_t self = pthread_self();
    printf("Thread %lu in signal handler\n", (long)self);
    if (signo == SIGINT) {
        longjmp(env[ENV_CTRLC], 1);                                             // Q?: Is it in the same thread ? (Never, Always, Sometimes?)
    }
    else 
    {
        printf("Other signal received..quitting.");                             // Ex: kill -9 pid
        exit(0);
    }
}

// thread timer function
void* timer_function(void* in_param)
{
    // Loop approx 100x per second.
    for (;;) {
        nanosleep((const struct timespec[]){{0, TICK_NS_TIME }}, NULL);         // Sleep 10 ms seconds.
        if (timeout_val) {
            if (!--timeout_val) {
                longjmp(env[ENV_TIMEOUT], 1);                                   // longjmp when timer reaches 0. (Q?: Is this valid with multithread?)
            }
        }
    }
}

// main
int main(int argc, char **argv)
{
    int i;
    int val;
    struct sigaction actions;
    pthread_t thread;
    setvbuf (stdout, NULL, _IONBF, 0);                                          // Make sure stdout is not buffered (ex:printf, etc.)
    printf("[Program started]\r\n");

    memset(&actions, 0, sizeof(actions));
    sigemptyset(&actions.sa_mask);
    actions.sa_flags = 0;
    actions.sa_handler = signal_handler;
    val = sigaction(SIGINT, &actions, NULL);  
    pthread_create(&thread, NULL, timer_function, NULL);                        // timer thread for example
    printf("[Timer thread started]\r\n");

    // setting env.
    val = setjmp(env[ENV_TIMEOUT]);
    if (val!=0){ printf("[JMP TIMEOUT]\r\n"); }

    val = setjmp(env[ENV_CTRLC]);
    if (val!=0){ printf("[JMP CTRLC]\r\n"); }

    // main loop
    timeout_val = TIMEOUT_COUNT;
    i = 0;
    for (;;)
    {
        i++;
        if (i > 10){ i = 0; printf("[%d]", timeout_val/TICK_PER_SEC); }         // Number of seconds before time out.
        sleep(1);
        printf(".");
    }
    printf("Main completed\n");
    return 0;
}
//Compile: g++ -pthread main.cpp -o main

Suggestion for alternative implementation would be great since I'm new to programming with threads !

3
  • 1
    There is no language C/C++. Only the different languages C and C++. C (which you tagged) has no exceptions. About the question: This is no consulting service. Your question is far too broad. What is confusing is that embedded MCUs typically don't have the standard library and no keyboard, so there is no ctrl-C. And handling timeouts with setjmp looks like a bad design to me. Jul 6, 2016 at 22:09
  • You can not safely call non-async-signal-safe functions such as printf() or exit() from within a signal handler. Jul 6, 2016 at 22:52
  • The original code was in C and using setjmp/longjmp. It was on a Freescale MCU (16 bits) which contains a CodeWarrior C standard library. The CTRLC was coming from the UART. I want a similar behavior but in C++ with thread. (hopefully removing the setjmp).
    – ssinfod
    Jul 7, 2016 at 2:16

1 Answer 1

7

setjmp() saves the information required to restore the calling environment. longjmp() can then restore this environment, but only within the same thread.

The C11 standard is explicit about the constraint of having the same thread:

7.13.2.1/2 If there has been no such invocation (i.e: of a previous setjmp), or if the invocation was from another thread of execution, or if the function containing the invocation of the setjmp macro has terminated execution in the interim, or if the invocation of the setjmp macro was within the scope of an identifier with variably modified type and execution has left that scope in the interim, the behavior is undefined.

In fact, setjmp/longjmp are generally implemented by saving the stack pointer so that restoring it makes sense only int the same execution context.

Alternative

Unless I've missed something, you use the second thread only to act as a timer. You could instead get rid of your POSIX pthread, and use a timer signal activated with POSIX timer_create().

But be aware that using setjmp/longjmp from a signal handler (so already in your original code for CTRL+C) is tricky, as explained in this SO answer. So you'd consider sigsetjmp/siglongjmp.

For the records: C or C++ ?

Your question is tagged C. But you mention c++ try and catch. So for the sake of completeness:

  • in C++ setjmp should be replaced by a try/catch and the longjmp by throwing an exception. setjmp/longjmp are supported in C++ only if unwinding the stack wouldn't require invocation of any non-trivial destructor (see C++ standard, 18.10/4).
  • the exceptions are not propagated across the threads, unless catched and explicitely rethrown using std::rethrow_exception(). It's delicate, so refer to this SO question for for additional details. But it's possible and could solve your issue.
3
  • The snippet was just an example. In my project, the thread is doing more work than just a simple nanosleep. Otherwise, I agree that timer_create would be better.
    – ssinfod
    Jul 7, 2016 at 2:28
  • Can we call longjmp from a signal handler ? In which thread is the signal handler running ? Is this random (because it is asynchronous) ? Would it be a solution to use pthread_kill to send the signal to a specific thread and then perform the longjmp ?
    – ssinfod
    Jul 7, 2016 at 3:04
  • Longjmp is not advised from a signal handler (see my remark about about siglongjmp+ link). For signal and threads see stackoverflow.com/q/11679568/3723423
    – Christophe
    Jul 7, 2016 at 6:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.