zoukankan      html  css  js  c++  java
  • GCD之after

    先介绍下C中的modf函数

    函数名:modf
    头文件:<math.h>
    函数原型:double modf(double x, double *ipart)
    函数用途:分解x,以得到x的整数和小数部分
    输入参数:x
    待分解的数输出参数:ipath x 的整数部分
    返回值:x 的小数部分
     

    多线程开发中,可能会有等待一段时间后再运行的情况,此时就用到了dispatch_after函数,调用该函数时第一个参数用的dispatch_time_t类型的值。该值使用dispatch_time函数或者dispatch_walltime函数完成。

    1.dispatch_time函数能够获取从第一个参数dispatch_tiem_t类型值指定的时间开始,到第二个参数指定的毫秒单位时间后的时间。第一个参数经常使用的值是之前源代码出现的DISPATCH_TIME_NOW,表示现在的时间。第二个参数是等待时间。该方法主要计算相对时间。

    1
    2
    3
    4
    5
    //#define NSEC_PER_SEC 1000000000ull  1秒
    //#define NSEC_PER_MSEC 1000000ull    1毫秒
    //#define USEC_PER_SEC 1000000ull     1毫秒
    //#define NSEC_PER_USEC 1000ull       1纳秒
    //ull                                 1皮秒 1毫微秒

     2.dispatch_walltime函数主要用于计算绝对时间。例如在dispatch_after函数想指定2015年03月27日11时11分11秒的这一绝对时间的情况,这可作为粗略的闹钟功能使用。在dispatch_walltime函数中要一个struct timespec类型的时间,该时间可以通过NSDate类对象完成。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    NSTimeInterval interval;
        double second,subsecond;
        struct timespec time;
        dispatch_time_t milestone;
        interval=[date timeIntervalSince1970];
        NSLog(@"%f",interval);
         
        subsecond=modf(interval, &second);
        NSLog(@"%f",second);
        NSLog(@"%f",subsecond);
        time.tv_sec=second;
        time.tv_nsec=subsecond*NSEC_PER_SEC;
         
        milestone=dispatch_walltime(&time, 0);
        NSLog(@"%llu",milestone);
        return milestone;

     3.运行该方法的结果如下图(主要是查看modf方法)

     4.学习完dispatch_time_t,下面再学习dispatch_after.

    dispatch_after函数并不是在指定的时间后执行处理,而只是在指定的时间追加处理到Dispatch Queue。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    NSDate *startDate=[NSDate date];
       NSLog(@"%@",startDate);
       dispatch_time_t time=dispatch_time(DISPATCH_TIME_NOW, 30*NSEC_PER_SEC);
       dispatch_after(time, dispatch_get_main_queue(), ^{
           NSLog(@"test");
           NSDate *endDate=[NSDate date];
           NSLog(@"%@",endDate);
       });
       NSDate *endDate=[NSDate date];
       NSLog(@"%@",endDate);

     5.运行结果

  • 相关阅读:
    linux 备份当前文件
    zz Apache 2.2.15 + PHP 5.3.2+ mysql windows环境配置
    zz iframe父子窗口间js方法调用
    批处理命令里获取本机的机器名
    Cache Concurrency Problem False Sharing
    因为添加assembly到GAC引起的Windows Azure Web Role部署失败
    求数组中满足a[i]<a[j]的相距最远的元素
    Dispose模式
    比较汇编指令 LEA 和 MOV
    读写Unicode字符串(UTF8,UTF16…)
  • 原文地址:https://www.cnblogs.com/yulei126/p/6783240.html
Copyright © 2011-2022 走看看