C 语言多线程 pthread 等待用户输入
#include<stdio.h>#include<unistd.h>
#include<malloc.h>
#include<pthread.h>
//函数参数封装
typedef struct WAIT
{
char *prompt;
char *res;
} *waitp;
void* wait_input(int wait_n, waitp str);
void* wait_input_thread(void* string);
int main(void)
{
char input_result = {0};
waitp wp = (waitp)malloc(sizeof(struct WAIT));
wp->res = input_result;
wp->prompt = "please enter within 3 seconds";
wait_input(3, wp);
printf("input_result = %s\n", wp->res);
return 0;
}
void* wait_input(int wait_n, waitp str)
{
pthread_t id;
if (!pthread_create(&id, NULL, (void*)&wait_input_thread, (void* )str))
{
printf("thread created successfully!"); //开启线程,返回 0 表示开启成功!
}
while (wait_n)
{
sleep(1);
if (str->res)
{
printf("%s\n", str->res);
break;
}
wait_n--;
}
pthread_cancel(id); //关闭线程
}
void* wait_input_thread(void* str)
{
waitp t = str;
printf("\n%s:\n", t->prompt);
scanf("%s", t->res);
}
页:
[1]