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++;
}
这里我生成两个线程。两个线程具有相同的字符串,实际上这个字符串是将从套接字中出来的最后一个字符串。为什么会发生这种情况,我该如何防止这种情况?请帮助我在这里呆了几天。
它的工作!谢谢。我也在我的代码中添加了strncpy和strncmp。我认为strncmp和strncpy是为了我的程序更快,对吧?导致如果我的缓冲区是缓冲区[256];用一个简单的strcpy我会复制所有的256个字符,而不仅仅是字符串或一个简单的strcmp我会比较所有256个字符结束不仅字符串。我也这么想。 – P3ett