runloop内部如何实现

一般来讲,一个线程一次只能执行一个任务,执行完成后线程就会退出。如果我们需要一个机制,让线程能随时处理事件但并不退出,通常的代码逻辑 是这样的:

1
2
3
4
5
6
7
function loop() {
    initialize();
    do {
        var message = get_next_message();
        process_message(message);
    while (message != quit);
}

或使用伪代码来展示下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// 
// http://weibo.com/luohanchenyilong/ (微博@iOS程序犭袁)
int main(int argc, char * argv[]) {
 //程序一直运行状态
 while (AppIsRunning) {
      //睡眠状态,等待唤醒事件
      id whoWakesMe = SleepForWakingUp();
      //得到唤醒事件
      id event = GetEvent(whoWakesMe);
      //开始处理事件
      HandleEvent(event);
 }
 return 0;
}

参考链接:《深入理解RunLoop》

posted @ 2017-02-25 21:13  昊天科技  阅读(264)  评论(0编辑  收藏  举报