문제

내가 쓴 나의 자신의 stop_watch 모듈이 있습니다.는 스레드를 생성하고의 기간 동안 초입니다.면 초가 만료되었을 것입 통 콜백 함수에서습니다.c 고 사용자에게 알리는 시간이 만료되었습니다.

이것은 그래서 그 사용자만이 3 초를 입력해 자리하고 그들 것이를 입력해야 5 자리 숫자가 있습니다.시간이 만료되면 프로그램을 중지합니다.

2 개의 문제입니다.1)면 그들은 입력하는 숫자에 필요한 시간입니다.는 방법을 취소할 수 있습니다.나는 생각하고 있었을 사용하여 thread_kill 또는 thread_cancel?2)할 수 있는 방법을 종료에 do_while 니까?로 scanf 을 차단하는 동안 기다리고 있을 입력하는 사용자를 위해.

많은 주셔서 감사합니다 제안,

내 아래 코드:

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

#include "stop_watch.h"

struct data_struct *g_data_struct;

void timeout_cb(int id)
{
    printf("Digit timeout\n");
    free(g_data_struct);
}

int main()
{
    pthread_t thread_id;
    unsigned int digit = 0;

    g_data_struct = (struct data_struct*) calloc(1, sizeof(*g_data_struct));

    if(!g_data_struct)
    {
        printf("=== failed to allocate memory ===\n");
        return 0;
    }

    /* start timer for 3 seconds */
    g_data_struct->seconds = 3;
    g_data_struct->func_ptr = timeout_cb;
    thread_id = start_stopwatch(g_data_struct);

    do
    {
        printf("Enter digit: ");
        scanf("%d", &digit);
    }while(1);

    pthread_join(thread_id, NULL);
    printf("=== End of Program - all threads in ===\n");

    free(g_data_struct);

    return 0;
}



#include <stdio.h>
#include <pthread.h>

#include "stop_watch.h"

pthread_t thread_id;
static id = 10;

/* start sleeping and call the callback when seconds have expired */
static void* g_start_timer(void *args)
{
    void (*function_pointer)(int id);
    int seconds = ((struct data_struct*) args)->seconds;
    function_pointer = ((struct data_struct*) args)->func_ptr;

    sleep(seconds);

    (void) (*function_pointer)(id);

    pthread_exit(NULL);

    return 0;
}

/* Will sleep in its own thread for a period of seconds */
int start_stopwatch(struct data_struct *g_data_struct)
{
    int rc = 0;

    int seconds = g_data_struct->seconds;
    printf("=== start_stopwatch(): %d\n", seconds);

    rc =  pthread_create(&thread_id, NULL, g_start_timer, (void *) g_data_struct);

    if(rc)
    {    
        printf("=== Failed to create thread\n");
        return 1;
    }

    return thread_id;
}

이 질문에 대한 C99gcc 니다.

도움이 되었습니까?

해결책

내가 권하고 싶지 않을 사용하여 별도의 스레드에서 이것에 대한 첫 번째 장소입니다.하지만 이처럼 운동을 사용하는 방법을 배울 스레드,내가 그것으로 이동.

당신은 설정할 수 있습 글로벌 boolean flag 는지 여부를 나타내는 숫자가 입력되었습니다.에 g_start_timer,단지를 호출하기 전에 function_pointer 지 여부를 확인 깃발을 설정되어 있습니다.는 경우에 그것은,부르지 않습니다.

당신이 원하는 스레드가 죽기 전에 그것의 잠 기간이 만료되면,사용할 수 있습니다 mutex try 잠급니다.

편집:때문에 당신이 그것을 말하지 않는 운동,난 언급은 어떻게 내가 그것을 할 것입니다.중 하나는 함수를 사용할 수 있는 시간 동안 입력을 기다리에 표준입력으로 select()또는 폴().또는,사용하는 경보()를 인터럽트.여기서 사용하는 예보:

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <errno.h>

void alarm_signal(int signum)
{
}

int main()
{
    char c;
    unsigned int v = 0;
    struct sigaction act;
    puts("Enter digit: ");

    /* Register dummy handler for alarm */
    act.sa_handler = &alarm_signal;
    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);
    sigaction(SIGALRM, &act, NULL);

    /* Set timer for 3 seconds */
    alarm(3);

    /* Read the digits */
    errno = 0;
    while(0 != read(STDIN_FILENO, &c, 1))
    {
        if(c < '0' || c > '9')
            break;
        v = v*10 + c - '0';
    }
    if(errno == EINTR)
        puts("Timed out");
    else
        printf("Value is %d\n", v);
    return 0;
}

다른 팁

물론 Thread_Cancel을 사용하여 스레드를 취소 할 수 있습니다. Scanf의 경우, 파이프를 사용하여 터미어의 입력을 시뮬레이션 할 수 있다고 생각할 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top