user3764213
user3764213

Reputation: 11

how to pass multiple arguments to thread for client server in c?

I want to create a concurrent server to work on multiple client request. So I created a thread function to handle multiple request . My problem is I have a hash table , it is loaded with contents of file initially whenever server start and I have socket descriptor, file descriptor too. So how can I pass to thread function .Is it required structure to store the arguments and pass to thread ?

my code is like this :

struct UserData
{
    char *username; 
    char *password;

};

struct HashTable
 {
    int size;
    struct UserData *table
 };

int main()
{
 struct HashTable *htable;
  //socket sd to open socket in server
  and a Fd file descriptor to write to file
 // hash table loaded with contents and it is a structure
 /*create thread using pthread*/
 pthread_create(...,fun,..);

 }

 void * fun(void *arg)
 {
  .............
  }

how I declare a structure for passing to thread function including the arguments like socket descriptor (sd) ,file descriptor(fd) and hash table pointer ? will I use mutex to lock when I writing to file (fd) ?

Upvotes: 1

Views: 1661

Answers (1)

Moldova
Moldova

Reputation: 1651

pthread_create() takes a void * as its final argument, which gets passed to your thread entry function, fun() in your case. So you would just need to define a struct that contains all the fields you want to pass:

struct ThreadArg {
    int sd; /* socket descriptor */
    int fd; /* file descriptor */
    struct HashTable *ht;
};

Then in your main() you fill it in and pass it to pthread_create():

...
struct ThreadArg *arg = malloc(sizeof(struct ThreadArg)); /* you should check for NULL */
arg->sd = sd;
arg->fd = fd;
arg->ht = htable;
pthread_create(..., fun, (void *)arg);
...

And in fun() you cast it back:

void *fun(void *arg) {
    struct ThreadArg *thArg = (struct ThreadArg *)arg;
    /* do whatever with thArg->sd, thArg->fd, etc. */
    ...
    /* free the memory when done */
    free(arg);
}

Upvotes: 2

Related Questions