0

I'm building a multi-threaded network chat program, but I can't figure out how to pass variables into pthread_create.

I have the following line of code that creates a thread:

pthread_create(&thread, NULL, receive, (void *) socket_fd);

My receive function looks like this:

void * receive(void * socket) {
    int socket_fd, response;
    char message[MESSAGE_BUFFER];
    socket_fd = (int) socket;

    while(true) {
        response = recvfrom(socket_fd, message, MESSAGE_BUFFER, 0, NULL, NULL);
        if (response) {
            printf("\nServer> %s", message);
            printf("%s", prompt);
        }
    }
}

How can I pass a prompt variable into this receive function, when calling receive in pthread_create?

1
  • Do you just want to pass a pointer to a struct? Just see the example here. Commented Feb 8, 2017 at 18:20

1 Answer 1

1

You can pack all of the data you want to pass to your thread on creation in a single struct and pass its pointer through the last parameter of pthread_create. in short:

define a struct:

typedef struct{
     char* prompt;
     int socket;
} thread_data;

and then call pthread_create:

thread_data data;
// place code here to fill in the struct members...
pthread_create(&thread, NULL, receive, (void *) &data);

in your receive function:

void * receive(void * threadData) {
    int socket_fd, response;
    char message[MESSAGE_BUFFER];

    thread_data* pData = (thread_data*)threadData;
    socket_fd = pData->socket;
    char* prompt = pData->prompt;

    while(true) {
        response = recvfrom(socket_fd, message, MESSAGE_BUFFER, 0, NULL, NULL);
        if (response) {
            printf("\nServer> %s", message);
            printf("%s", prompt);
        }
    }
}

Hope this helps.

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

2 Comments

But one must be careful with this if one passes (a pointer to) the same struct in more than one call to pthread_create(), and any of those threads or the parent thread also modifies the struct. Proper synchronization is required in such a case.
You are absolutely correct. This is simply the most basic solution and it does not show any synchronization and locking mechanism that's required in the case of a shared resource.

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.