1

Suppose the server handles clients in the following manner:

void* handle_request(void* client_sck);

int client_sck;

while((client_sck = accept(...)) != -1)
{
    /*
    .
    .
    .
    */
    
    pthread_create(&thr, 0, handle_request, (void*)&client_sck);    
}

Is it safe to say that, on each loop iteration, the last argument passed to pthread_create will be shared among threads? Meaning the second time a around, the client_sck still has the same address from the previous iteration.

4
  • You're referencing the same variable, why would the address ever change? However, this is most likely not what you want. Commented Aug 22, 2020 at 0:43
  • You know apache httpd (and othres) is open source right? You can go have a look. Commented Aug 22, 2020 at 2:53
  • 1
    The address will not change, but the dereferenced value will be different. That is going to be a problem if the thread created first-time-round has not dereferencd it yet:( Commented Aug 22, 2020 at 7:20
  • So, we can conclude that, this is not the smartest way to handle client connections, due to the address essentially being the same, but the value is overwritten on each iteration. Is mallocing a new argument for each iteration before the call to pthread_create the right move ? @Nic3500 I'm curious about a more simplistic example of an http server rather than a full-blown project. Mostly due to the nature of pthread_create Commented Aug 22, 2020 at 8:02

1 Answer 1

1

Yes. This means that the next accept() can overwrite the value before the previous thread had a chance to fetch the value, so it's not a good design.

Sign up to request clarification or add additional context in comments.

1 Comment

What you think of this approach ? stackoverflow.com/questions/8719888/… I've never practiced casting an int to void* (or vice versa). The comments to this answer suggest that it doesn't create the problem I described in the question and avoids the use of malloc.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.