Created
April 15, 2026 17:37
-
-
Save 3dgoose/d148d0d3dc78f51c47dd445b0d1ca65d to your computer and use it in GitHub Desktop.
Mutex for threading
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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