我已经编写了自己的 stop_watch 模块。这将创建一个线程并休眠几秒钟。一旦秒数过期,它将调用 main.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;
}
顺便说一句,这个问题是关于 C99 gcc 的。