LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Try for a configurable time and quit (https://www.linuxquestions.org/questions/programming-9/try-for-a-configurable-time-and-quit-4175417609/)

grob115 07-19-2012 09:52 AM

Try for a configurable time and quit
 
Hi, am writing a C++ program that needs to execute a function, provided with a lib, that may hang resulting in the whole thread getting stuck. If I want to say wait for only a few seconds and then move on, is there a way to do this? Thanks.

dmdeb 07-19-2012 03:31 PM

Quote:

Originally Posted by grob115 (Post 4732760)
Hi, am writing a C++ program that needs to execute a function, provided with a lib, that may hang resulting in the whole thread getting stuck. If I want to say wait for only a few seconds and then move on, is there a way to do this? Thanks.

Hi grob115,

now that sounds like a strange library function! Why does it behave like that? Is that really within its specification?

Anyway: You could create a new thread (man pthread_create), call that weird library function in that (using your own wrapper function), and monitor how that goes from your main thread. But to me, that sounds like a lot of work for just calling a library function...

Regards
dmdeb

dmdeb 07-19-2012 03:57 PM

Some example code for that (hanger.c):

Code:

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

static int done = 0;

void obnoxious_library_function(void)
{
    if (random() % 2)
    {
        printf( "OK.\n" );
    }
    else
    {
        printf( "Hanging...\n" );
        sleep( 60 );
    }
}

void* my_wrapper(void *genarg)
{
    assert( genarg == NULL );

    done = 0;
    obnoxious_library_function( );
    done = 1;

    return NULL;
}

int main(void)
{
    for (;;)
    {
        pthread_t  thread;
        int        ret;

        ret = pthread_create( &thread, NULL, &my_wrapper, NULL );
        assert( ret == 0 );

        sleep( 1 );

        if (!done)
        {
            void  *result;

            ret = pthread_cancel( thread );
            assert( ret == 0 );

            ret = pthread_join( thread, &result );
            assert( result == PTHREAD_CANCELED );
        }
    }
}

Makefile example:

Code:

CFLAGS=-W -Wall -Werror -pedantic
LDFLAGS=-pthread
CC=gcc

all: hanger

But again: That library function behavior sounds really weird.


All times are GMT -5. The time now is 03:16 PM.