Joseph-Matteo-Scorsone/ConcurrentHashMap
Hashmap that avoids the use of a Mutex until the need for resizing for better concurrency with the use of atomic values.
Hashmap that avoids the use of a Mutex until the need for resizing for better concurrency with the use of atomic values.
put
, get
, remove
, and iteration, ensuring safe concurrent access.Written with Zig 0.14.0
Clone this repository:
git clone https://github.com/Joseph-Matteo-Scorsone/ConcurrentHashMap.git
Integrate in build.zig
const concurrent_HashMap = b.createModule(.{
.root_source_file = b.path("ConcurrentHashMap/src/concurrentHashMap.zig"),
});
exe_mod.addImport("concurrent_HashMap", concurrent_HashMap);
const std = @import("std");
const ConcurrentHashMap = @import("concurrent_HashMap").ConcurrentHashMap;
pub fn main() !void {
const allocator = std.heap.page_allocator;
var map = try ConcurrentHashMap(u64, u64, std.hash_map.AutoContext(u64)).init(allocator, 16, .{});
defer map.deinit();
try map.put(1, 100);
try map.put(2, 200);
try map.put(3, 300);
var iter = map.iterator();
defer iter.deinit();
while (iter.next()) |entry| {
std.debug.print("Key: {any}, Value: {any}\n", .{entry.key, entry.value});
}
}
ConcurrentHashMap(comptime K: type, comptime V: type).init(allocator: *Allocator, initial_capacity: usize) !ConcurrentHashMap(K, V)
Initializes a new concurrent hash map.
Parameters:
K
: Key type (must be hashable)V
: Value typeallocator
: Memory allocatorinitial_capacity
: Starting size of the hashmapReturns: Initialized ConcurrentHashMap(K, V)
Errors: May fail if allocation fails
deinit(self: *ConcurrentHashMap(K, V)) void
Frees all resources used by the hashmap.
put(self: *ConcurrentHashMap(K, V), key: K, value: V) !void
Inserts or updates a key-value pair.
!void
get(self: *ConcurrentHashMap(K, V), key: K) ?V
Fetches the value associated with a key.
?V
: Value if presentnull
: If key is not in mapremove(self: *ConcurrentHashMap(K, V), key: K) bool
Removes a key-value pair.
true
if key was present and removedfalse
if key was not founditerator(self: *ConcurrentHashMap(K, V)) Iterator
Returns an iterator to traverse the map safely (not thread-safe during concurrent writes).
next(self: *Iterator) ?struct { key: K, value: V }
count(self: *ConcurrentHashMap(K, V)) usize
Returns the current number of elements in the hashmap.
capacity(self: *ConcurrentHashMap(K, V)) usize
Returns the current number of total slots in the hashmap.
zig build test
Ensure that all tests pass to verify the correctness of the implementation.
Contributions are welcome! If you have suggestions, bug reports, or enhancements, please open an issue or submit a pull request.
This project is licensed under the MIT License. See the LICENSE file for details.