父线程用标志变量控制子线程的范例

来源:互联网 发布:java猜拳游戏代码 编辑:程序博客网 时间:2024/05/19 04:26

       在实际开发中, 我们会碰到太多需要开线程的例子, 通常会让子线程异步地处理一些信息。 一旦某些情况发生后, 我们需要在父线程中让子线程终止, 那则么办呢? 一个自然而言的想法是用标志变量控制

       通用范例如下:

#include <stdio.h>#include <pthread.h>#define YES 0#define NO -1int exitFlag = NO;void *threadFun(void *p){while(NO == exitFlag){printf("hello\n");sleep(1);}}int main(){pthread_t id;pthread_create(&id, NULL, threadFun, NULL);getchar();exitFlag = YES;return 0;}
      结果如下: (在执行过程中, 我按了Enter键, 改变exitFlag的值, 从而使得子线程退出)

[taoge@localhost learn_c]$ gcc test.c -lpthread
[taoge@localhost learn_c]$ ./a.out 
hello
hello
hello
hello


[taoge@localhost learn_c]$ 


       好了, 其实很简单, 也很常见很常用, 本文仅仅小小记录一下。





       

0 0
原创粉丝点击