OpenCyphal / libcanard

A compact implementation of the Cyphal/CAN protocol in C for high-integrity real-time embedded systems

Home Page:http://opencyphal.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

The problem of thread safety

Linjieqiang opened this issue · comments

commented

Do we need to consider adding a thread safety protection mechanism to the libcanard library. In my project, I added the following code for it. But I think the api should expose the corresponding interface.

static TX_MUTEX mutex_uavcan_tx;

void canard_thread_safe_wrap_init(void)
{
    tx_mutex_create(&mutex_uavcan_tx, "uavcan tx", TX_NO_INHERIT);
}

int32_t canardTxPushThreadSafe(CanardInstance *const ins, const CanardTransfer *const transfer)
{
    tx_mutex_get(&mutex_uavcan_tx, TX_WAIT_FOREVER);
    int32_t res = canardTxPush(ins, transfer);
    tx_mutex_put(&mutex_uavcan_tx);

    return res;
}

const CanardFrame *canardTxPeekThreadSafe(const CanardInstance *const ins)
{
    const CanardFrame *frame;

    tx_mutex_get(&mutex_uavcan_tx, TX_WAIT_FOREVER);
    frame = canardTxPeek(ins);
    tx_mutex_put(&mutex_uavcan_tx);

    return frame;
}

void canardTxPopThreadSafe(CanardInstance *const ins)
{
    tx_mutex_get(&mutex_uavcan_tx, TX_WAIT_FOREVER);
    canardTxPop(ins);
    tx_mutex_put(&mutex_uavcan_tx);
}

I don't think we should because synchronization is highly platform-dependent and it would introduce capabilities that are only needed for a subset of applications.

Agree with Pavel. Synchronization should be provided as a wrapper if needed. Ideally one does not need synchronization and, instead, relies on lockless patterns like optimistic concurrency or queues built using atomic primitives.