Skip to content

Instantly share code, notes, and snippets.

@3dgoose
Created April 15, 2026 17:37
Show Gist options
  • Select an option

  • Save 3dgoose/d148d0d3dc78f51c47dd445b0d1ca65d to your computer and use it in GitHub Desktop.

Select an option

Save 3dgoose/d148d0d3dc78f51c47dd445b0d1ca65d to your computer and use it in GitHub Desktop.
Mutex for threading
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char *data;
size_t size;
size_t capacity;
pthread_mutex_t lock;
} Buffer;
void buffer_init(Buffer *buf, size_t initial_capacity) {
buf->data = malloc(initial_capacity);
buf->size = 0;
buf->capacity = initial_capacity;
pthread_mutex_init(&buf->lock, NULL);
}
void buffer_write(Buffer *buf, const char *input, size_t len) {
pthread_mutex_lock(&buf->lock);
if (buf->size + len > buf->capacity) {
size_t new_capacity = buf->capacity * 2 + len;
char *new_data = realloc(buf->data, new_capacity);
if (new_data) {
buf->data = new_data;
buf->capacity = new_capacity;
} else {
// handle allocation failure
pthread_mutex_unlock(&buf->lock);
return;
}
}
memcpy(buf->data + buf->size, input, len);
buf->size += len;
pthread_mutex_unlock(&buf->lock);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment