C threading question

Question

Hi,

​

I followed a tutorial for a simple multi-threaded TCP socket server, and my main question is why do we have to allocate heap memory to remember the FD of the accepted socket? If we pass the accepted socket by value to a simple function would it still work?

From my basic understanding of OS, I think it is because a pointer to the stack will always point to a specific location, so if we passed a reference to it there would be a data race condition between the threads and the while loop(correct me if I'm wrong).

I understand that pthread_create takes a void pointer, so we cannot just pass by value, but if we encased it in a struct by value then pass a reference to that struct into the new function. If we did this would we still have the data race?

Code below, removed the socket init boilerplate for brevity:

while (1)
    {
        printf("\n~~~~~~~~~Waiting to accept a new conn~~~~~~~~\n\n\n");
        int accepted_socket;

        check(accepted_socket = accept(server_file_d, (struct sockaddr *)&incoming_addr, &addrlen), "Failed to accept connection");

        pthread_t thread;

        int *p_accepted_socket = malloc(sizeof(int));

        *p_accepted_socket = accepted_socket;

        pthread_create(&thread, NULL, &handle_conn_wrapper, p_accepted_socket);
    }

Posted Dec 6, 2020, 11:49 PM UTC

911
Loading comments…