diff --git a/threads/build.zig b/threads/build.zig new file mode 100644 index 0000000..f05a414 --- /dev/null +++ b/threads/build.zig @@ -0,0 +1,22 @@ +const std = @import("std"); + +pub fn build(b: *std.build.Builder) void { + const target = b.standardTargetOptions(.{}); + const optimize = b.standardOptimizeOption(.{}); + + { + const exe = b.addExecutable(.{ + .name = "threads-simple", + .root_source_file = .{ .path = "main.c" }, + .optimize = optimize, + .target = target + }); + exe.linkLibC(); + + const run_cmd = b.addRunArtifact(exe); + const run_step = b.step("run", "Run simple program"); + run_step.dependOn(&run_cmd.step); + + b.installArtifact(exe); + } +} diff --git a/threads/main.c b/threads/main.c new file mode 100644 index 0000000..cc61b0c --- /dev/null +++ b/threads/main.c @@ -0,0 +1,54 @@ +#include +#include +#include + +struct shared_data { + pthread_mutex_t mutex; + int counter; +}; + +struct thread_args { + const char *name; + struct shared_data *shared; +}; + +void *thread_callback(void *p) { + struct thread_args *args = p; + struct shared_data *data = args->shared; + + for (int i = 0; i < 100000; i++) { + if (pthread_mutex_lock(&data->mutex) != 0) { + perror("pthread_mutex_lock"); + } + + data->counter++; + + if (pthread_mutex_unlock(&data->mutex) != 0) { + perror("pthread_mutex_unlock"); + } + } + + return NULL; +} + +int main() { + struct shared_data shared_data = { 0 }; + + if (pthread_mutex_init(&shared_data.mutex, NULL) < 0) { + printf("Failed to initialise mutex\n"); + return -1; + } + + pthread_t thread1; + struct thread_args args1 = { "Thread 1", &shared_data }; + pthread_create(&thread1, NULL, thread_callback, &args1); + + pthread_t thread2; + struct thread_args args2 = { "Thread 2", &shared_data }; + pthread_create(&thread2, NULL, thread_callback, &args2); + + pthread_join(thread1, NULL); + pthread_join(thread2, NULL); + + printf("Counter is %d\n", shared_data.counter); +}