为什么我的链表空了?

时间:2014-12-15 22:56:18

标签: c multithreading struct linked-list

我有一个链表。当我在线程中时,我的列表不为空并打印(例如):

LISTE = Dan
LISTE = 4

当我在main()中的wile(1)中时,SAME列表为空并打印一个空行。问题是它没有进入" for"。你知道问题是什么吗?

感谢您的帮助。

PS:套接字不是问题

struct User {
  char pseudo[PSEUDO_MAX];
  int socket;
  struct User *next;
};


struct Thread {
  struct User* lst;
  fd_set* readfds;
  int* max;
  int socket;
  pthread_mutex_t* mutex;
};


void add(struct User** pp, const char *t, const int sock)
{
    struct User *p = malloc(sizeof(*p));
    strcpy(p->pseudo, t);
    p->socket = sock;
    p->next = NULL;

    while (*pp)
        pp = &(*pp)->next;
    *pp = p;
}


void print(const struct User* n) 
{
    for ( ; n; n = n->next ){
        printf("LISTE : %s\n", n->pseudo);
        printf("LISTE : %d\n", n->socket);
    }
    printf("\n");
}

void *thread_pseudo(void *arg)
{
  struct Thread* ps_thread = (struct Thread*)arg;
  int nsock = ps_thread->socket;
  pthread_mutex_t* mutex = ps_thread->mutex;
  pthread_mutex_lock(mutex);
  struct User* lst = ps_thread->lst;
  int* max = ps_thread->max;
  fd_set* readfds = ps_thread->readfds;
  pthread_mutex_unlock(mutex);

    pthread_mutex_lock(mutex);
    // ...
    *max = (nsock < *max ? *max : nsock);

    // ...

    add(&lst, pseudo, nsock);

    print(lst); // HERE IT'S NOT EMPTY
    pthread_mutex_unlock(mutex);
    pthread_exit(NULL);
}


int main()
{
  pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;


  int sockfd2, new_fd;
  int max;
  struct sockaddr_in my_addr;
  struct sockaddr_in their_addr;
  unsigned int sin_size;
  int yes=1;
  struct User *lst = NULL;
  struct Thread *ps_thread = malloc(sizeof(*ps_thread));
  fd_set readfds;


  // ...



  while(1){
    FD_ZERO(&readfds);
    FD_SET(sockfd2, &readfds);
    print(lst); // HERE IT'S EMPTY

    //...
        pthread_t thread; 
        ps_thread->lst = lst;
        ps_thread->readfds = &readfds;
        ps_thread->max = &max;
        ps_thread->socket = new_fd;
        ps_thread->mutex = &mutex;

        if (pthread_create(&thread, NULL, thread_pseudo, ps_thread)) {
        perror("pthread_create");
        return EXIT_FAILURE;
        }

        // ...
    } 

0 个答案:

没有答案