简体   繁体   中英

Preventing Thread Specific Data From Being Overwritten C

I am trying to create a simple chat program in C. For each client, I am creating a new thread so the server can handle communicating with multiple users at once. I am storing each user data in a stucture as follows:

struct User                     /*structure to handle all clients*/
{
    int port;
    char username[10];
    struct User*connected;
    struct User*next;
};

In the main thread, I create a new thread and pass in the structure for the user:

 pthread_create(&thr,NULL,server,(void*)&args);

This is done for each user.

Now, when each new thread is created, i copy the user structure from the arguments to be used in the thread.

   void *server(void * arguments) 
    {
          struct User*cur_user = arguments; 
    }

This works fine for the first user, however, when a new user joins, the information from the arguments is overwritten.

I understand that threads share data in a program. However, is there a way I can copy the arguments and same them to a local variable in the thread so they are only thread scope? In other words, how can I use the cur_user variable within the thread without having other threads modify its contents?

EDIT:

I tried to copy the memory but I am not having much luck:

struct User args;                     
        struct User*new_arg = malloc(sizeof(struct *new_arg));
        memcpy(new_arg, *args, sizeof(new_arg))

Is something wrong with my malloc?

A pointer is just a pointer. You're giving each thread a pointer to the same args structure. So they each have their own pointer but they all point to the same thing. Since they all then access the arguments through their pointer, they all access the same arguments.

You need to actually give each one of them their own structure, not just their own pointer to the same structure. Allocate a new structure with malloc(), fill it in, and hand it to the server/thread (which needs to free() it before it dies.)

If you can stomach gcc -specific solutions, consider the __thread storage class .

Otherwise, consider using pthread_key_create() / pthread_get_specific() + pthread_set_specific() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM