Handle-with-cache.c
// Cache miss - load the resource pthread_mutex_unlock(&cache_lock); // Unlock during I/O UserProfile *profile = load_user_profile_from_disk(user_id); pthread_mutex_lock(&cache_lock);
pthread_mutex_unlock(&cache_lock); } The cache_lock mutex protects the hash table, but note that get_handle() releases the lock during the actual load_user_profile_from_disk() call. This is crucial to avoid blocking all threads during I/O. However, it introduces a race condition where two threads might simultaneously miss the cache and both load the same resource. handle-with-cache.c
A handle cache solves this by storing active handles in a key-value store after the first access. Subsequent requests bypass the expensive operation and return the cached handle directly. A well-written handle-with-cache.c typically contains four main sections: 1. The Handle and Cache Structures First, we define our handle type (opaque to the user) and the cache entry. A handle cache solves this by storing active
In systems programming, efficiency is paramount. Repeatedly opening, reading, or computing the same resource (a file, a network socket, a database row, or a complex calculation result) is wasteful. This is where caching becomes indispensable. The Handle and Cache Structures First, we define
The module handle-with-cache.c exemplifies a classic design pattern: the . A "handle" is an opaque pointer or identifier to a resource, and the cache stores recently accessed handles to avoid redundant initialization or I/O operations.
GHashTableIter iter; gpointer key, value; g_hash_table_iter_init(&iter, handle_cache); while (g_hash_table_iter_next(&iter, &key, &value)) { CacheEntry *entry = value; if (entry->ref_count == 0 && (now - entry->last_access) > max_age_seconds) { to_remove = g_list_prepend(to_remove, key); } }