Is it safe to cast the osThreadId pointer to a 32-bit integer for a unique thread ID across platform

Hey friends, Porting a product to a CMSIS RTOS. We need a 32-bit integer representing the thread ID. While
osThreadId
osThreadId
is opaque, comments suggest it's a pointer. Is it safe to cast the
osThreadId
osThreadId
pointer to a 32-bit integer for a unique thread ID across platforms? Why or why not? @Middleware & OS
Solution:
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 👇 ```c...
Jump to solution
2 Replies
Solution
Enthernet Code
Enthernet Code•7mo ago
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;
}
Want results from more Discord servers?
Add your server