0%

Grand Central Dispatch (libdispatch)

在整理Concurrency programming資料的時候,發現這個部份被我遺漏了,寫點東西免得忘記。
libdispatch 是由蘋果開發的Concurrency framework,如今也可以在FreeBSD上使用。

FreeBSD Wiki上找來的範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <dispatch/dispatch.h>

#include <err.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
dispatch_queue_t q;
dispatch_time_t t;

q = dispatch_get_main_queue();
t = dispatch_time(DISPATCH_TIME_NOW, 5LL * NSEC_PER_SEC);

// Print a message and exit after 5 seconds.
dispatch_after(t, q, ^{
printf("block_dispatch\n");
exit(0);
});

dispatch_main();
return (0);
}

看到那個 ^{ .... } 區塊的部份就類似於其他語言的Closure,C++11的lambda expression
至於要編譯這段程式碼,就需要

1
# clang -Wall -Werror -fblocks -L/usr/local/lib -I/usr/local/include -o test test.c -ldispatch

Blocks是Clang的Extension,更多資訊可以參考Programming with C Blocks,GCC不支援,至於libdispatch需要在ports下事先安裝。編譯的時候要記得加上-fblockss
當然,也可以有無Blocks的版本。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <dispatch/dispatch.h>

#include <err.h>
#include <stdio.h>
#include <stdlib.h>

void
deferred_code(__unused void *arg)
{

printf("block_dispatch\n");
exit(0);
}

int main(int argc, char *argv[])
{
dispatch_queue_t q;
dispatch_time_t t;

q = dispatch_get_main_queue();
t = dispatch_time(DISPATCH_TIME_NOW, 5LL * NSEC_PER_SEC);

dispatch_after_f(t, q, NULL, deferred_code);

dispatch_main();
return (0);
}

編譯的時候就可以拿掉-fblocks

1
# clang -Wall -Werror -I/usr/local/include -L/usr/local/lib -o test2 test2.c -ldispatch

除了Cuncurrency之外,Closure的觀念也在很多程式語言開枝散葉了。

這個pdf有對libdispatch作個簡單的介紹。
在各語言下都有類似libdispatch這樣的Framework