Compare commits

...

8 Commits

Author SHA1 Message Date
df551a7653 add memory mapped files example 2024-01-06 21:36:40 +02:00
15b0378545 add shmat example 2024-01-06 21:22:15 +02:00
7761accd98 update build.zig in threads 2024-01-06 21:09:44 +02:00
48e0a65413 update forking example 2024-01-06 21:09:38 +02:00
ea173678f2 add shm_open example 2024-01-06 21:09:34 +02:00
e4e5710eef add threads example 2024-01-06 15:34:00 +02:00
dd6a6b0e5e update forking example 2024-01-06 15:32:23 +02:00
7321708c66 update formatting 2024-01-06 14:51:42 +02:00
11 changed files with 497 additions and 84 deletions

20
file-mmap/build.zig Normal file
View File

@ -0,0 +1,20 @@
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 = "mmap-example",
.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);
}

114
file-mmap/main.c Normal file
View File

@ -0,0 +1,114 @@
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct shared_data {
pthread_mutex_t mutex;
int counter;
};
struct shm_shared_data {
int file_fd;
struct shared_data *shared_data;
};
void increment_counter(struct shared_data *data) {
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");
}
}
}
struct shm_shared_data shared_data_open() {
// Open or create a file
int fd = open("/tmp/shared_memory", O_CREAT | O_RDWR, 0666);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
int shm_size = sizeof(struct shared_data);
// Set the size of the file
if (ftruncate(fd, shm_size) == -1) {
perror("ftruncate");
exit(EXIT_FAILURE);
}
// Map the file into the process address space
struct shared_data *shared_data = mmap(NULL, shm_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (shared_data == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
struct shm_shared_data shm_shared_data = {
.file_fd = fd,
.shared_data = shared_data
};
return shm_shared_data;
}
void shared_data_close(struct shm_shared_data shm_data) {
// Unmap the shared memory
if (munmap(shm_data.shared_data, sizeof(struct shared_data)) == -1) {
perror("munmap");
exit(EXIT_FAILURE);
}
// Close the file
if (close(shm_data.file_fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
}
void *thread_callback(void *p) {
struct shm_shared_data shm_data = shared_data_open();
increment_counter(shm_data.shared_data);
shared_data_close(shm_data);
return NULL;
}
int main() {
struct shm_shared_data shm_data = shared_data_open();
pthread_mutexattr_t mutex_attr;
pthread_mutexattr_init(&mutex_attr);
pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED);
shm_data.shared_data->counter = 0;
if (pthread_mutex_init(&shm_data.shared_data->mutex, &mutex_attr) < 0) {
printf("Failed to initialise mutex\n");
return -1;
}
pthread_t thread1;
pthread_create(&thread1, NULL, thread_callback, NULL);
pthread_t thread2;
pthread_create(&thread2, NULL, thread_callback, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Counter is %d\n", shm_data.shared_data->counter);
shared_data_close(shm_data);
return 0;
}

View File

@ -4,10 +4,9 @@ pub fn build(b: *std.build.Builder) void {
const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{});
{
const exe = b.addExecutable(.{
.name = "forking-simple",
.root_source_file = .{ .path = "simple.c" },
.name = "forking-example",
.root_source_file = .{ .path = "main.c" },
.optimize = optimize,
.target = target
});
@ -19,20 +18,3 @@ pub fn build(b: *std.build.Builder) void {
b.installArtifact(exe);
}
{
const exe = b.addExecutable(.{
.name = "forking-mutexes",
.root_source_file = .{ .path = "mutexes.c" },
.optimize = optimize,
.target = target
});
exe.linkLibC();
const run_cmd = b.addRunArtifact(exe);
const run_step = b.step("run-mutexes", "Run mutexes program");
run_step.dependOn(&run_cmd.step);
b.installArtifact(exe);
}
}

View File

@ -8,45 +8,23 @@
#include <stdbool.h>
#include <time.h>
// WARNING: This example does not work, I couldn't figure out why the child process goes into a deadlock on `pthread_mutex_lock`
struct shared_data {
pthread_mutex_t mutex;
int counter;
};
void milli_sleep(int milliseconds) {
struct timespec ts;
ts.tv_sec = milliseconds / 1000;
ts.tv_nsec = (milliseconds % 1000) * 1000000;
nanosleep(&ts, &ts);
}
float random_float() {
return (float)rand()/(float)RAND_MAX;
}
int random_range(int from, int to) {
return random_float()*(to-from) + from;
}
void run(const char *name, struct shared_data *data) {
printf("[%s] started, mutex: %p\n", name, &data->mutex);
for (int i = 0; i < 10; i++) {
void increment_counter(const char *name, struct shared_data *data) {
for (int i = 0; i < 10000; i++) {
if (pthread_mutex_lock(&data->mutex) != 0) {
perror("pthread_mutex_lock");
}
int counter = data->counter;
milli_sleep(random_range(0, 100));
data->counter = counter + 1;
printf("[%s] counter is %d\n", name, counter + 1);
data->counter++;
if (pthread_mutex_unlock(&data->mutex) != 0) {
perror("pthread_mutex_unlock");
}
}
printf("[%s] finished\n", name);
}
int main() {
@ -55,8 +33,11 @@ int main() {
perror("mmap");
return -1;
}
pthread_mutexattr_t mutex_attr;
pthread_mutexattr_init(&mutex_attr);
pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED);
if (pthread_mutex_init(&shared_data->mutex, NULL) < 0) {
if (pthread_mutex_init(&shared_data->mutex, &mutex_attr) < 0) {
printf("Failed to initialise mutex\n");
return -1;
}
@ -66,14 +47,16 @@ int main() {
int pid = fork();
if (pid == 0) {
srand(time(NULL)+1);
run("Child ", shared_data);
increment_counter("Child ", shared_data);
return 0;
} else {
srand(time(NULL)+2);
run("Parent", shared_data);
increment_counter("Parent", shared_data);
}
int child_status;
waitpid(pid, &child_status, 0);
printf("Counter is %d\n", shared_data->counter);
}

View File

@ -1,27 +0,0 @@
#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
int main() {
char parent_message[] = "hello";
char child_message[] = "goodbye";
void* shmem = mmap(NULL, 128, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
memcpy(shmem, parent_message, sizeof(parent_message));
int pid = fork();
if (pid == 0) {
printf("Child read: %s\n", (char*)shmem);
memcpy(shmem, child_message, sizeof(child_message));
printf("Child wrote: %s\n", (char*)shmem);
} else {
printf("Parent read: %s\n", (char*)shmem);
sleep(1);
printf("After 1s, parent read: %s\n", (char*)shmem);
}
}

20
shm_open/build.zig Normal file
View File

@ -0,0 +1,20 @@
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 = "shm-open-example",
.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);
}

122
shm_open/main.c Normal file
View File

@ -0,0 +1,122 @@
#include <sys/mman.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <stdbool.h>
#define SHM_NAME "/shared_memory"
struct shared_data {
pthread_mutex_t mutex;
int counter;
};
struct shm_shared_data {
int shm_fd;
struct shared_data *shared_data;
};
void increment_counter(struct shared_data *data) {
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");
}
}
}
struct shm_shared_data shared_data_open() {
struct shared_data *shared_data;
// Create or open a shared memory object
int shm_fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if (shm_fd == -1) {
perror("shm_open");
exit(EXIT_FAILURE);
}
int shm_size = sizeof(struct shared_data);
if (ftruncate(shm_fd, shm_size) == -1) {
perror("ftruncate");
exit(EXIT_FAILURE);
}
// Map the shared memory object into the process's address space
shared_data = mmap(NULL, shm_size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (shared_data == MAP_FAILED) {
perror("mmap");
exit(EXIT_FAILURE);
}
struct shm_shared_data shm_shared_data = {
.shm_fd = shm_fd,
.shared_data = shared_data
};
return shm_shared_data;
}
void shared_data_close(struct shm_shared_data shm_data) {
// Unmap the shared memory and close the file descriptor
if (munmap(shm_data.shared_data, sizeof(struct shared_data)) == -1) {
perror("munmap");
exit(EXIT_FAILURE);
}
if (close(shm_data.shm_fd) == -1) {
perror("close");
exit(EXIT_FAILURE);
}
}
void *thread_callback(void *p) {
struct shm_shared_data shm_data = shared_data_open();
increment_counter(shm_data.shared_data);
shared_data_close(shm_data);
return NULL;
}
int main() {
struct shm_shared_data shm_data = shared_data_open();
pthread_mutexattr_t mutex_attr;
pthread_mutexattr_init(&mutex_attr);
pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED);
if (pthread_mutex_init(&shm_data.shared_data->mutex, &mutex_attr) < 0) {
printf("Failed to initialise mutex\n");
return -1;
}
pthread_t thread1;
pthread_create(&thread1, NULL, thread_callback, NULL);
pthread_t thread2;
pthread_create(&thread2, NULL, thread_callback, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Counter is %d\n", shm_data.shared_data->counter);
shared_data_close(shm_data);
// Unlink the shared memory object (aka delete shared memory)
if (shm_unlink(SHM_NAME) == -1) {
perror("shm_unlink");
exit(EXIT_FAILURE);
}
return 0;
}

20
shmat/build.zig Normal file
View File

@ -0,0 +1,20 @@
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 = "shmat-example",
.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);
}

105
shmat/main.c Normal file
View File

@ -0,0 +1,105 @@
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct shared_data {
pthread_mutex_t mutex;
int counter;
};
struct shm_shared_data {
int shm_id;
struct shared_data *shared_data;
};
void increment_counter(struct shared_data *data) {
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");
}
}
}
struct shm_shared_data shared_data_open() {
key_t key = ftok("shmfile", 65); // Generate a key for the shared memory segment
// Create a shared memory segment
int shm_id = shmget(key, sizeof(struct shared_data), 0666 | IPC_CREAT);
if (shm_id == -1) {
perror("shmget");
exit(EXIT_FAILURE);
}
// Attach the shared memory segment to the address space of the process
struct shared_data *shared_data = shmat(shm_id, NULL, 0);
if (shared_data == (void*)-1) {
perror("shmat");
exit(EXIT_FAILURE);
}
struct shm_shared_data shm_shared_data = {
.shm_id = shm_id,
.shared_data = shared_data
};
return shm_shared_data;
}
void shared_data_close(struct shm_shared_data shm_data) {
// Detach the shared memory segment
if (shmdt(shm_data.shared_data) == -1) {
perror("shmdt");
exit(EXIT_FAILURE);
}
}
void *thread_callback(void *p) {
struct shm_shared_data shm_data = shared_data_open();
increment_counter(shm_data.shared_data);
shared_data_close(shm_data);
return NULL;
}
int main() {
struct shm_shared_data shm_data = shared_data_open();
pthread_mutexattr_t mutex_attr;
pthread_mutexattr_init(&mutex_attr);
pthread_mutexattr_setpshared(&mutex_attr, PTHREAD_PROCESS_SHARED);
if (pthread_mutex_init(&shm_data.shared_data->mutex, &mutex_attr) < 0) {
printf("Failed to initialise mutex\n");
return -1;
}
pthread_t thread1;
pthread_create(&thread1, NULL, thread_callback, NULL);
pthread_t thread2;
pthread_create(&thread2, NULL, thread_callback, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Counter is %d\n", shm_data.shared_data->counter);
shared_data_close(shm_data);
// Remove the shared memory segment
if (shmctl(shm_data.shm_id, IPC_RMID, NULL) == -1) {
perror("shmctl");
exit(EXIT_FAILURE);
}
return 0;
}

20
threads/build.zig Normal file
View File

@ -0,0 +1,20 @@
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-example",
.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
View 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);
}