Enthernet Code
Enthernet Code
DIIDevHeads IoT Integration Server
Created by Dtynin on 6/24/2024 in #middleware-and-os
Is it safe to cast the osThreadId pointer to a 32-bit integer for a unique thread ID across platform
Hi @Dtynin , Casting a osThreadId pointer to a 32-bit integer is generally not safe and should be avoided, instead you can try maintain a mapping or using a 64-bit Integer. this is how your code should look like for maintaining a map 👇
#include <stdint.h>
#include <stdlib.h>

#define MAX_THREADS 128

typedef struct {
osThreadId threadId;
uint32_t uniqueId;
} ThreadMapping;

ThreadMapping threadMappings[MAX_THREADS];
uint32_t nextUniqueId = 1;

uint32_t getThreadUniqueId(osThreadId threadId) {
for (int i = 0; i < MAX_THREADS; i++) {
if (threadMappings[i].threadId == threadId) {
return threadMappings[i].uniqueId;
}
}

// If thread ID not found, add new mapping
for (int i = 0; i < MAX_THREADS; i++) {
if (threadMappings[i].threadId == NULL) {
threadMappings[i].threadId = threadId;
threadMappings[i].uniqueId = nextUniqueId++;
return threadMappings[i].uniqueId;
}
}

// Handle case where no space is left for new threads
// This can be expanded based on your application's requirements
return 0;
}
#include <stdint.h>
#include <stdlib.h>

#define MAX_THREADS 128

typedef struct {
osThreadId threadId;
uint32_t uniqueId;
} ThreadMapping;

ThreadMapping threadMappings[MAX_THREADS];
uint32_t nextUniqueId = 1;

uint32_t getThreadUniqueId(osThreadId threadId) {
for (int i = 0; i < MAX_THREADS; i++) {
if (threadMappings[i].threadId == threadId) {
return threadMappings[i].uniqueId;
}
}

// If thread ID not found, add new mapping
for (int i = 0; i < MAX_THREADS; i++) {
if (threadMappings[i].threadId == NULL) {
threadMappings[i].threadId = threadId;
threadMappings[i].uniqueId = nextUniqueId++;
return threadMappings[i].uniqueId;
}
}

// Handle case where no space is left for new threads
// This can be expanded based on your application's requirements
return 0;
}
4 replies