Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Post History

50%
+0 −0
Q&A How to correctly model the delay timer for a CHIP8 emulator written in C?

I asked this question in SE a while back. TL;DR I need to emulate a timer in C that allows concurrent writes and reads, whilst preserving constant decrements at 60 Hz (not exactly, but approxima...

1 answer  ·  posted 4d ago by aura-lsprog-86‭  ·  last activity 4d ago by aura-lsprog-86‭

#1: Initial revision by user avatar aura-lsprog-86‭ · 2025-02-17T07:46:06Z (4 days ago)
How to correctly model the delay timer for a CHIP8 emulator written in C?
_I asked this question in [SE](https://stackoverflow.com/q/38339445/5397930) a while back._

<hr />

**TL;DR** I need to emulate a timer in C that allows concurrent writes and reads, whilst preserving constant decrements at 60 Hz (not exactly, but approximately accurate). It will be part of a Linux CHIP8 emulator. Using a thread-based approach with shared memory and semaphores raises some accuracy problems, as well as race conditions depending on how the main thread uses the timer.

_Which is the best way to devise and implement such a timer?_

<hr />

I am writing a Linux CHIP8 interpreter in C, module by module, in order to dive into the world of emulation.

I want my implementation to be as accurate as possible with the specifications. In that matter, timers have proven to be the most difficult modules for me.

Take for instance the delay timer. In the specifications, it is a "special" register, initally set at 0. There are specific opcodes that set a value to, and get it from the register.

If a value different from zero is entered into the register, it will automatically start decrementing itself, at a frequency of 60 Hz, stopping once zero is reached.

My idea regarding its implementation consists of the following:

1. The use of an ancillary thread that does the decrementing automatically, at a frequency of nearly 60 Hz by using `nanosleep()`. I use `fork()` to create the thread for the time being.
2. The use of shared memory via `mmap()` in order to allocate the timer register and store its value on it. This approach allows both the ancillary and the main thread to read from and write to the register.
3. The use of a semaphore to synchronise the access for both threads. I use `sem_open()` to create it, and `sem_wait()` and `sem_post()` to lock and unlock the shared resource, respectively.

The following code snippet illustrates the concept:

    void *p = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
    /* Error checking here */

    sem_t *mutex = sem_open("timersem", O_CREAT, O_RDWR, 1);
    /* Error checking and unlinking */

    int *val = (int *) p;
    *val = 120; // 2-second delay

    pid_t pid = fork();

    if (pid == 0) {
        // Child process
        while (*val > 0) { // Possible race condition
            sem_wait(mutex); // Possible loss of frequency depending on main thread code
            --(*val); // Safe access
            sem_post(mutex);
            /* Here it goes the nanosleep() */
        }
    } else if (pid > 0) {
        // Parent process
        if (*val == 10) { // Possible race condition
            sem_wait(mutex);
            *val = 50; // Safe access
            sem_post(mutex);
        }
    }

A potential problem I see with such implementation relies on the third point. If a program happens to _update_ the timer register once it has reached a value _different from zero_, then the ancillary thread **must not** wait for the main thread to unlock the resource, or else the 60 Hz delay will not be fulfilled. This implies both threads may freely update and/or read the register (constant writes in the case of the ancillary thread), which obviously introduces race conditions.

Once I have explained what I am doing and what I try to achieve, my question is this:

_Which is the best way to devise and emulate a timer that allows concurrent writes and reads, whilst preserving an acceptable fixed frequency?_