2017-05-26 91 views
1

我有一个函数会生成多个线程,我每次都会向它们传递一个不同的字符串,但似乎线程具有相同的字符串。字符串来自一个插座。这里是代码:无法将不同的字符串传递给多个线程

pthread_t *MirrorManager; 

MirrorManager = malloc(sizeof(pthread_t)*th_size); 
if(MirrorManager == NULL) { perror("malloc"); exit(1); } 
/* -------------------------------------- */ 

int th_num = 0; 

while(true) 
{ 
    received = 0; 

    /* Read the desired readable size */ 
    if(read(newsock, &size, sizeof(size)) < 0) 
    { perror("Read"); exit(1); } 

    /* Read all data */ 
    while(received < size) 
    { 
     if((nread = read(newsock, buffer + received, size - received)) < 0) 
     { perror("Read"); exit(1); } 

     received += nread; 
    } 

    if(strcmp(buffer, "end") == 0) { break; } 


    printf("Received string: %s\n",buffer); 

    /* Create thread */ 
    strcpy(th_str, buffer); 
    if((err = pthread_create(&MirrorManager[th_num], NULL, thread_start, (void*) th_str)) == true) 
    { show_error("pthread_create", err); } 

    /* Take next thread */ 
    th_num++; 
} 

这里我生成两个线程。两个线程具有相同的字符串,实际上这个字符串是将从套接字中出来的最后一个字符串。为什么会发生这种情况,我该如何防止这种情况?请帮助我在这里呆了几天。

回答

0

您应该发布完整的代码。

鉴于你已经发布的东西,它看起来像你的问题是,所有的线程共享相同的参数th_str

pthread_create(&MirrorManager[th_num], NULL, thread_start, (void*) th_str)) 

相反,你应该分配为每个线程单独th_str,因为你为每个线程传递一个指针,而不是字符串本身。

th_str = malloc(strlen(buffer)); 
strcpy(th_str, buffer); 

然后一定要让每个线程释放传入它的指针。 PS:我强烈建议在套接字的所有数据上使用strncmpstrncpy

+0

它的工作!谢谢。我也在我的代码中添加了strncpy和strncmp。我认为strncmp和strncpy是为了我的程序更快,对吧?导致如果我的缓冲区是缓冲区[256];用一个简单的strcpy我会复制所有的256个字符,而不仅仅是字符串或一个简单的strcmp我会比较所有256个字符结束不仅字符串。我也这么想。 – P3ett