I'm asking this question because I learned about implementing thread-safe, dynamically resizable arrays in C from a book, where it was presented as an essential topic for understanding advanced c programing and concurrency control.
Loading
I'm asking this question because I learned about implementing thread-safe, dynamically resizable arrays in C from a book, where it was presented as an essential topic for understanding advanced c programing and concurrency control.
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Aman GuptaRank #193 · 12.4K reputationPosted Jul 2, 2024, 8:50 AM EDT
Hi Himaja,
In C, you can use pthreads for threading and synchronization. Here's a simple implementation:
#include #include #include typedef struct { int *array; size_t size; size_t capacity; pthread_mutex_t lock; } ThreadSafeArray; void initArray(ThreadSafeArray *a, size_t initialCapacity) { a->array = (int *)malloc(initialCapacity * sizeof(int)); a->size = 0; a->capacity = initialCapacity; pthread_mutex_init(&(a->lock), NULL); } void insertArray(ThreadSafeArray *a, int element) { pthread_mutex_lock(&(a->lock)); if (a->size == a->capacity) { a->capacity *= 2; a->array = (int *)realloc(a->array, a->capacity * sizeof(int)); } a->array[a->size++] = element; pthread_mutex_unlock(&(a->lock)); } void freeArray(ThreadSafeArray *a) { pthread_mutex_destroy(&(a->lock)); free(a->array); } int main() { ThreadSafeArray a; initArray(&a, 5); // Example usage insertArray(&a, 1); insertArray(&a, 2); freeArray(&a); return 0; }In C++, you can use the
std::vectorfor dynamic arrays andstd::mutexfor synchronization.#include #include #include class ThreadSafeVector { public: void insert(int value) { std::lock_guard guard(mutex_); vec_.push_back(value); } void print() { std::lock_guard guard(mutex_); for (const auto &val : vec_) { std::cout vec_; std::mutex mutex_; }; int main() { ThreadSafeVector tsVec; // Example usage tsVec.insert(1); tsVec.insert(2); tsVec.print(); return 0; }