LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 950|回复: 1

关于多线程的问题

[复制链接]
发表于 2008-1-3 10:42:35 | 显示全部楼层 |阅读模式
#include <stdio.h>
#include <pthread.h>
void *aaa(void *arg)
{
        printf("thread started!\n");
        while(1)
        {
                printf("in thread!\n");
                sleep(1);
        }
        printf("thread exit!\n");
        return NULL;
}

int main(void)
{
        pthread_t thrd;
        int static i;
        pthread_create(&thrd,NULL,aaa, NULL);
        while(1)
        {
                i++;
                printf("in main!\n");
                sleep(1);
                if(i==6)
                        pthread_cancel(thrd);
        }
        return 0;
}

原希望在pthread_cancel之后线程会退出while循环,打印出”thread exit!“,不知怎么样改可以做到,谢谢了
发表于 2008-1-3 11:24:06 | 显示全部楼层

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

  3. static short iFlag = 0;

  4. void *aaa(void *arg)
  5. {
  6.         printf("thread started!\n");
  7.         while(iFlag > 0)
  8.         {
  9.                 printf("in thread!\n");
  10.                 sleep(1);
  11.         }
  12.         printf("thread exit!\n");
  13.         return NULL;
  14. }

  15. int main(void)
  16. {
  17.         pthread_t thrd;
  18.         int i;

  19.         iFlag = 1;

  20.         pthread_create(&thrd,NULL,aaa, NULL);

  21.         for (i = 0; i < 10; i++)
  22.         {
  23.                 printf("in main!\n");
  24.                 sleep(1);
  25.                 if(i==6)
  26.                         iFlag = 0;
  27.         }
  28.         return 0;
  29. }

复制代码
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表