1
Answer

How to implement thread-safe dynamic array?

Photo of K Himaja

K Himaja

1y
602
1

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.

Answers (1)

2
Photo of Aman Gupta
38 35.2k 2.5m 1y

Hi Himaja,

In C, you can use pthreads for threading and synchronization. Here's a simple implementation:

#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>

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::vector for dynamic arrays and std::mutex for synchronization.

#include <vector>
#include <mutex>
#include <iostream>

class ThreadSafeVector {
public:
    void insert(int value) {
        std::lock_guard<std::mutex> guard(mutex_);
        vec_.push_back(value);
    }

    void print() {
        std::lock_guard<std::mutex> guard(mutex_);
        for (const auto &val : vec_) {
            std::cout << val << " ";
        }
        std::cout << std::endl;
    }

private:
    std::vector<int> vec_;
    std::mutex mutex_;
};

int main() {
    ThreadSafeVector tsVec;

    // Example usage
    tsVec.insert(1);
    tsVec.insert(2);
    tsVec.print();

    return 0;
}