pthread和select()函数的用途是什么?

时间:2016-04-19 04:00:52

标签: c linux unix select pthreads

我们的教授在课堂上给了我们这段代码:

st = select(max+1, &rs, NULL, NULL, &timeinterval);

 if(st){ 
        for(int i=0; i<workers; i++)
        {

            if(FD_ISSET(channels[i]->read_fd(), &rs))
我真的很难理解它在做什么。我试图研究更多关于pthreads的内容,但似乎没有任何东西可以解释这是做什么的。他说它与文件描述符有关,但我不知道这是如何在这段代码中。

1 个答案:

答案 0 :(得分:2)

这个rs的目的是等待多个文件描述符,可能超时,当它返回一个正数时,这意味着if(st > 0) { for(int i=0; i<workers; i++) { if(FD_ISSET(channels[i]->read_fd(), &rs)) { // perform read on channels[i]->read_fd } } } else if (st == 0) { // handle time out } else { // handle error } 集合中至少有一个fd准备就绪用于读取,以便在循环中检查它是哪个fd,并对其执行读取。

注意,你应该检查大于0,因为如果出现错误,将返回-1,你不应该检查fd_set但是处理错误:

from pprint import pprint
input = [{"id":"BMW_1_Series",
        "years":[{"id":10052,"year":2008,
                    "styles":[{"id":560,"name":"128i 2",
                               "submodel":{"body":"Conver","niceName":"conve"},"trim":"128i"},
                              {"id":561,"name":"135i ",
                               "submodel":{"body":"Conver","niceName":"conver"},"trim":"135i"}
                              ]
                  },
                 {"id":427,"year":2016,
                  "styles":[{"id":433,"name":"228i ",
                             "submodel":{"body":"Conve", "niceName":"conver"},"trim":"228i SULEV"},
                            {"id":431,"name":"M235i",
                             "submodel":{"body":"Coupe", "niceName":"m235i"},"trim":"M235i"}
                            ]
                  }
                 ]
          }
         #I deleted the other entries, but it is a list
         ]
ds=input[0]["years"][0]
pprint(ds)
def flatten_ds(ds, final_ds={},  prepend_tag=None):
    if type(ds) is dict:
        for k, v in ds.iteritems():
            if not (type(v) is list or type(v) is dict):
                if prepend_tag:
                    k = prepend_tag + '_' + k
                final_ds[k] = v
            else:
                final_ds =  flatten_ds(v, prepend_tag=k, final_ds=final_ds)
        return final_ds

        return final_ds
    if type(ds) is list:
        for d in ds:
            final_ds = flatten_ds(d, prepend_tag=prepend_tag, final_ds=final_ds)
            return final_ds

pprint(flatten_ds(ds))