怎么理解state thread 库(2)

来源:互联网 发布:淘宝发布宝贝时间段 编辑:程序博客网 时间:2024/06/01 10:22

我分析程序,一般首先是分析它的线程模型。看看一共有几个线程,各个线程都干了什么。

但分析st-thread库,就比较迷茫了。因为它本身有个线程模块,其实是一个堆里的数据块,并没有真正的线程。我曾经怀疑,在st_ini里,有两次创建线程的机会,一个是一个idle_therad,一个是自带第一个线程。但仔细分析代码。还是没有真正的线程创建。莫非是外部创建线程,通过某种巧妙的方法,传给st库?看public.h接口里,也没有这样的数据。比较迷茫了。只好亲自写代码测试。



刚好st自带了测试程序,比较简单的就是那个lookdns的程序。代码如下:

线程函数

void *do_resolve(void *host){  struct in_addr addr;  /* Use dns_getaddr() instead of gethostbyname(3) to get IP address */  if (dns_getaddr(host, &addr, TIMEOUT) < 0) {    fprintf(stderr, "dns_getaddr: can't resolve %s: ", (char *)host);    if (h_errno == NETDB_INTERNAL)      perror("");    else      herror("");  } else    printf("%-40s %s\n", (char *)host, inet_ntoa(addr));  return NULL;}
主函数

int main(int argc, char *argv[]){  int i;  if (argc < 2) {    fprintf(stderr, "Usage: %s <hostname1> [<hostname2>] ...\n", argv[0]);    exit(1);  }  if (st_init() < 0) {    perror("st_init");    exit(1);  for (i = 1; i < argc; i++) {    /* Create a separate thread for each host name */    if (st_thread_create(do_resolve, argv[i], 0, 0) == NULL) {      perror("st_thread_create");      exit(1);    }  }  st_thread_exit(NULL);  /* NOTREACHED */  return 1;}

测试方法是在主函数中增加slleep函数,看看线程函数和主函数是否一起运行。修改后的主函数如下

int main(int argc, char *argv[]){  int i;  if (argc < 2) {    fprintf(stderr, "Usage: %s <hostname1> [<hostname2>] ...\n", argv[0]);    exit(1);  }  if (st_init() < 0) {    perror("st_init");    exit(1);  }  for (i = 1; i < argc; i++) {    /* Create a separate thread for each host name */    if (st_thread_create(do_resolve, argv[i], 0, 0) == NULL) {      perror("st_thread_create");      exit(1);    }  }  for (i = 0;i<10;i++){  printf("main thread begin sleep %d \n",i);  sleep(1);}  st_thread_exit(NULL);  /* NOTREACHED */  return 1;

编译,输出结果如下

主线程阻塞了线程函数的运行,可以确定的是,使用st库,st本身并不会创建任何线程。他会使用调用st_ini()函数的线程做为调用它的运行线程。


那么下一个问题。怎么用的呢?


0 0
原创粉丝点击