Re: Asynchronous timers (without a run loop)
Re: Asynchronous timers (without a run loop)
- Subject: Re: Asynchronous timers (without a run loop)
- From: "Michael Ash" <email@hidden>
- Date: Fri, 5 Dec 2008 10:43:25 -0500
On Fri, Dec 5, 2008 at 7:52 AM, Påhl Melin <email@hidden> wrote:
> The reason I asked for a simple Timer API without using a run loop is
> because I'm converting my framework from Dotnet where such a Timer API
> exists and makes it dead simple to setup multiple timers without
> blocking or setting up a dedicated thread in each process for just
> handling the timers. In C++/CLI using Dotnet you just specify:
>
> Timer^ myTimer = gcnew Timer(gcnew TimerCallback(&TimerFunction),
> nullptr, 5000, 500);
>
> ...to have the TimerFunction() function be called twice per second
> after 5 seconds (time in millisecond). Nothing else – you don't need
> to idle your thread at all. Dotnet handles everything by itself.
> Setting up multiple timers is just repeating the line of code above.
> (gcnew is just new on the garbage collect heap and the carret '^' is
> just a pointer/handle to the garbage collect heap if you don't know
> Microsoft C++/CLI)
If you use a CFRunLoopTimer then your code will be roughly as simple
as that. All you need to do is spawn off a thread at the beginning of
your program and have it sit inside CFRunLoopRun. Store a reference to
its runloop somewhere, and then install timers on it. CFRunLoop is
thread safe, so you can easily and directly create timers and schedule
them on your timer thread's runloop without any extra protection.
Of course you will have to write some setup code to create that timer
thread. But this will be perhaps ten lines of code.
And of course your timer callbacks will end up running in a separate
thread, which mean you'll have to worry about thread safety. But given
the API above, I imagine something similar must be happening there, so
that won't be a big change.
Mike
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden