add threads example
This commit is contained in:
parent
dd6a6b0e5e
commit
e4e5710eef
22
threads/build.zig
Normal file
22
threads/build.zig
Normal file
@ -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);
|
||||
}
|
||||
}
|
54
threads/main.c
Normal file
54
threads/main.c
Normal file
@ -0,0 +1,54 @@
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <pthread.h>
|
||||
|
||||
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);
|
||||
}
|
Loading…
Reference in New Issue
Block a user