Pthread confusion

I have confusion regarding pthreads return value.
All in short , is the is a valid return value ?

1
2
3
4
5
6
7
8

void * myThrRoutine(void *arg)
{
struct myStruct **myst = (struct myStruct**) arg;
cout<<"In thread "<<(*myst)->var<<(*myst)->msg<<endl;
int x = 20;
pthread_exit((void*)x);
}



This seems to work fine on pthread_join , but i want to ensure it is not by chance...

Thanks...
I've seen similar examples in text books.

you may possibly get a warning on a 64 bit machine
int from void *.

I believe that technically speaking it is not valid, however I do not know what section
of the standard talks about pointers to invalid memory locations. (However I was
told by a friend who knows the standard far better than me that it is invalid).
You're returning the address of a variable on the stack. When the function exits the variable will no longer be valid and the memory may be reused by something else.

The syntax is correct although you should use reinterpret_cast, but it doesn't make much sense.
well no, it's not returning an address, just sticking an int into the space of a void pointer.
so there are issues,
this code will compile on my old laptop but on my AMD64 I get:
error: cast from 'void*' to 'int' loses precision
but if I make it long it will compile


1
2
3
4
5
6
7
8
9
10
11
#include <cstdio>

void * pop()
{
    return (void *) 17;
}

int main(int argc, char ** argv) {

    printf("i got:%d\n", (int) pop());
}


examples like this exists in a famous pthread text book .

BUT it says...

pthread_join is just a covenience for the simplest and most limited means of conveying a threads results.


Last edited on
I'd be tempted to return new int(x);
bigearsbilly
well no, it's not returning an address,

You're right, my mistake. In which case, it's ok. But I'd still recomend using reinterpret_cast.

Windows programs do that sort of thing all the time, stuffing data into the WPARAM and LPARAM args when passing information using Windows messages.


Galik
I'd be tempted to return new int(x);

It's probably better not to hit the heap just for this.
I am back from the secret RHL lab.....as of now this is not recommended.... the local variable gets destroyed on return. So you need to hit the heap.

Traditionally i guess the values get copied back. I tried the same with a structure with a const/dest defined. Turns out , the destructor is called ....and the object references are hay-wire......

I'll get back to the lab and try out some more stuff!

Cheers!
Last edited on
Topic archived. No new replies allowed.