|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- #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[20] = {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[0])
- {
- 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);
- }
复制代码 |
|