标签:des style class blog code http
功能:
实现多线程:2个线程同时工作,一个用时间计数器,一个用来打印信息
STEP1
XCODE -》New Application -》Cocoa中的Command Line
自动增加:
#include <CoreFoundation/CoreFoundation.h>
STEP2
//
// main.c
// test_runloop1
//
// Created by DMD on 20/6/14.
// Copyright (c) 2014 EDU. All rights reserved.
//
/*
Test Thread
*/
#include <CoreFoundation/CoreFoundation.h>
// Just for this c file.
static int g_vid=1;
static void _perform(void *info __unused)
{
printf("No %d. hello,\n",g_vid);
g_vid++;
}
static void _timer(CFRunLoopTimerRef timer __unused, void *info)
{
g_vid++;
CFRunLoopSourceSignal(info);
}
int main(int argc, const char * argv[])
{
// insert code here...
CFRunLoopSourceRef source;
CFRunLoopSourceContext source_context;
// 第一个线程:执行自定义的函数:_perform
bzero(&source_context, sizeof(source_context));
//调用要执行的函数
source_context.perform = _perform;
//声称循环源
source = CFRunLoopSourceCreate(NULL, 0, &source_context);
//将循环源增加到当前线程里面去
CFRunLoopAddSource(CFRunLoopGetCurrent(), source, kCFRunLoopCommonModes);
// 第二个线程:一个时间计数器
CFRunLoopTimerRef timer;
CFRunLoopTimerContext timer_context;
bzero(&timer_context, sizeof(timer_context));
timer_context.info = source;
//生成时间循环源
timer = CFRunLoopTimerCreate(NULL, CFAbsoluteTimeGetCurrent(), 1, 0, 0,
_timer, &timer_context);
//增加时间循环器
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer, kCFRunLoopCommonModes);
CFRunLoopRun();
return 0;
}//
// main.c
// test_runloop1
//
// Created by DMD on 20/6/14.
// Copyright (c) 2014 EDU. All rights reserved.
//
/*
Test Thread
*/
#include <CoreFoundation/CoreFoundation.h>
// Just for this c file.
staticint g_vid=1;
staticvoid _perform(void *info__unused)
{
printf("No %d. hello,\n",g_vid);
g_vid++;
}
staticvoid _timer(CFRunLoopTimerRef timer __unused, void *info)
{
g_vid++;
CFRunLoopSourceSignal(info);
}
int main(int argc,const char * argv[])
{
// insert code here...
CFRunLoopSourceRef source;
CFRunLoopSourceContext source_context;
// 第一个线程:执行自定义的函数:_perform
bzero(&source_context, sizeof(source_context));
//调用要执行的函数
source_context.perform =_perform;
//声称循环源
source =CFRunLoopSourceCreate(NULL,0, &source_context);
//将循环源增加到当前线程里面去
CFRunLoopAddSource(CFRunLoopGetCurrent(), source,kCFRunLoopCommonModes);
//第二个线程:一个时间计数器
CFRunLoopTimerRef timer;
CFRunLoopTimerContext timer_context;
bzero(&timer_context, sizeof(timer_context));
timer_context.info = source;
//生成时间循环源
timer = CFRunLoopTimerCreate(NULL,CFAbsoluteTimeGetCurrent(), 1,0, 0,
_timer, &timer_context);
//增加时间循环器
CFRunLoopAddTimer(CFRunLoopGetCurrent(), timer,kCFRunLoopCommonModes);
CFRunLoopRun();
return 0;
}
如图
测试成功!
完
参考:
http://blog.csdn.net/onlyou930/article/details/7423161
MAC COCOA一个简单的多线程程序,布布扣,bubuko.com
标签:des style class blog code http
原文地址:http://blog.csdn.net/u013317006/article/details/32721129