Here it is, in the context of pthread.h and stdint.h:
struct arguments {
uint32_t threads;
uint32_t size;
};
void *run_v1(void *arg) {
uint32_t thread = (uintptr_t) arg;
for (uint32_t j = 0; j < arguments.size; ++j) {
size_t global_index = get_global_index(thread, j);
char *string = get_string(global_index);
hash_table_v1_add_entry(hash_table_v1, string, global_index);
}
return NULL;
}
...
int main () {
...
for (uintptr_t i = 0; i < arguments.threads; ++i) {
int err = pthread_create(&threads[i], NULL, run_v1, (void*) i);
if (err != 0) {
printf("pthread_create returned %d\n", err);
return err;
}
}
...
}
This is my professor's code, I read the specification here:
The following type designates an unsigned integer type with the property that any valid pointer to void can be converted to this type, then converted back to a pointer to void, and the result will compare equal to the original pointer: uintptr_t
Why is the cast to this type necessary, rather than passing in a uint32_t and casting to itself? Is this undefined behavior?
It is not, but if
uint32_tis smaller thanuintptr_tyou may get a warning about "cast from pointer to integer of different size".uintptr_ton the other hand is defined to be able to store pointer values as integers.When the cast to
uintptr_tis done you may still get a warning about "implicit conversion loses integer precision", so if what you've stored in thevoid*was actually anuint32_tto start with, add a cast to not get that potential warning:However, I suggest sending in the value via a pointer and then you wouldn't need any explicit casts:
A more elaborate example of making use of passing a pointer which is easy to extend if your thread needs more data than a single
uint32_tcould look like this: