OS X(Cocoa等)创建可取消的周期性操作的惯用方法

时间:2015-07-25 15:02:02

标签: objective-c multithreading macos cocoa pthreads

是否存在OSX / Cocoa惯用方法来创建执行定期操作的可取消线程,即

/* Needed windows definitions by following header */
#include <windef.h>
/* Windows performance data helper */
#include <Pdh.h>

/* Storage of PDH query and associated cpu counter */
struct cpu_counter{
    PDH_HQUERY query;
    PDH_HCOUNTER counter;
};

/* Initialize query & counter */
int cpu_counter_init(struct cpu_counter* pcc)
{
    if(PdhOpenQueryA(NULL, 0, &pcc->query) != ERROR_SUCCESS)
        return -1;
    if(PdhAddEnglishCounterA(pcc->query, "\\Processor(_Total)\\% Processor Time", 0, &pcc->counter) != ERROR_SUCCESS || PdhCollectQueryData(pcc->query) != ERROR_SUCCESS)
    {
        PdhCloseQuery(pcc->query);
        return -2;
    }
    return 0;
}

/* Fetch data from query and evaluate current counter value */
int cpu_counter_get(struct cpu_counter* pcc)
{
    PDH_FMT_COUNTERVALUE counter_val;
    if(PdhCollectQueryData(pcc->query) != ERROR_SUCCESS || PdhGetFormattedCounterValue(pcc->counter, PDH_FMT_LONG, NULL, &counter_val) != ERROR_SUCCESS)
        return -1;
    return counter_val.longValue;
}

/* Close all counters of query and query itself at the end */
void cpu_counter_close(struct cpu_counter* pcc)
{
    if(pcc->query != NULL)
    {
        PdhCloseQuery(pcc->query);
        pcc->query = NULL;
    }
}

在POSIX中,可以使用线程,条件变量和标志创建它;我写了一篇simple implementation(链接到gist;为了简洁而在问题中省略),但它确实是一本教科书的例子。正如您所看到的,代码行很多,我确信这样一个典型的东西有一个简单的解决方案。

我考虑的选项:

  • while not cancelled: cancelable sleep for N seconds if sleep was cancelled: return else: do periodic task 提供相同的语义,但在UI线程上执行。

  • Grand Central Dispatch(GCD)没有取消,我希望能够尽快取消该行动。

1 个答案:

答案 0 :(得分:1)

使用NSOperationQueueNSOperation。这些类使用gcd。可以使用NSOperation操作取消cancel