user11047992
user11047992

Reputation:

Passing socket to thread instead of fd?

Im using this function to accept a new client and pass it to a thread

struct sockaddr_in client;
while(1) {
    len = sizeof(client);
    fd = accept(sock, (struct sockaddr*)&client, &len);
    if(fd>0) {
        CreateThread(NULL, 0, process_thread, (LPVOID)fd, 0, &thread);
        // pthread_create( &thread , NULL , process_thread , (int)fd);
    }
}

and handle it like

DWORD WINAPI process_thread(LPVOID lpParam) {
//void process_thread(int sock) {
    SOCKET fd = (SOCKET)lpParam;
    //int fd = sock;
    ....  
}

Can i also create a new thread with the client structure (sockaddr_in) and pick the fd inside the handler function like

CreateThread(NULL, 0, process_thread, (SOCKET)client, 0, &thread);

and how? And if so how to accept after creating the thread? Is this possible?

Thank you

Upvotes: 1

Views: 267

Answers (1)

What you should do is create a new struct to hold both your values:

struct process_thread_info
{
    struct sockaddr_in client;
    SOCKET fd;
};

and then you can pass this structure:

// We must use malloc to create a new struct for every client.
// We can't just declare one here and then use its address,
// because it might go out of scope before the process_thread receives the info.
struct process_thread_info *threadinfo = malloc(sizeof(struct process_thread_info));
threadinfo->fd = fd;
threadinfo->client = client;

CreateThread(NULL, 0, process_thread, threadinfo, 0, &thread);
// pthread_create( &thread , NULL , process_thread , threadinfo);

As with any other usage of malloc, don't forget to have the thread free the struct when it's finished using it.

Upvotes: 1

Related Questions