I've been following the instructions on creating POSIX threads, and closely following their example Pthread Creation and Termination.
According to their example, they pass a long integer value to pthread_create(), which results in a call similar to this one:
pthread_create(&thread, NULL, do_something, (long*)testVal);
A sketch of the code I want to run is:
#include <iostream>
#include <pthread.h>
using namespace std;
// Simple example class.
class Range {
public:
int start;
int end;
Range(int start_bound, int end_bound) {
start = start_bound;
end = end_bound;
}
void print() {
cout << "\n(" << start << ", " << end << ')';
}
};
void* do_something(void* testVal) {
std::cout << "Value of thread: " << (long)testVal << '\n';
pthread_exit(NULL);
}
int main() {
pthread_t thread;
Range range = Range(1, 2); // What I really want to pass
long testVal = 42; // Let's test
pthread_create(&thread, NULL, do_something, (void*)testVal);
pthread_exit(NULL);
}
This is in the context of an assignment where the teacher wants us to use gcc in Linux, so I'm using Windows Subsystem for Linux with these compilation parameters:
gcc program.cpp -o program -lstdc++ -lpthread
Running the above program will output "Value of thread: 42".
My C++ pointer experience is a few years behind me, but just for fun, let's change the datatype from long to int. This changes the statements to int testVal = 42 and std::cout << "Value of thread: " << (int)testVal << '\n';. However, this happens:
error: cast from ‘void*’ to ‘int’ loses precision (int)testVal
warning: cast to pointer from integer of different size pthread_create(&thread, NULL, do_something, (void*)testVal);
Using an integer datatype is not what I want to do, but I include this case because my guess is that the problem compounds from here.
Question
How do I pass the Range object to pthread_create()? I need to do something like,
void* do_something(void* range) {
(Range)range.print();
...
...but am confronted with a bunch of type errors. Researching other questions about passing this value has not brought much clarity. The main problem that comes back is invalid cast from type 'Range' to type 'void*'. I'm not versed enough in the difference between passing a void pointer to a value to versus passing a void pointer to an addressed type to understand what's going wrong. Testing various combinations of pointer reference, dereference, and casting has not helped.
(void*)&testValaddress of testVal