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.

monolith937
  • 429
  • 1
  • 4
  • 13
  • You're referencing the same variable, why would the address ever change? However, this is most likely not what you want. – vmt Aug 22 '20 at 00:43
  • You know apache httpd (and othres) is open source right? You can go have a look. – Nic3500 Aug 22 '20 at 02: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:( – Martin James Aug 22 '20 at 07: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 `malloc`ing 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` – monolith937 Aug 22 '20 at 08:02

1 Answers1

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.

Volker Stolz
  • 7,274
  • 1
  • 32
  • 50
  • What you think of this approach ? https://stackoverflow.com/questions/8719888/freeing-argument-in-function-specified-in-pthread-create#answer-8719973 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`. – monolith937 Aug 22 '20 at 08:45