pthreads 以意想不到的方式填充缓冲区

pthreads fill buffer in unexpected way

我正在尝试在简单的 TCP/IP 服务器客户端通信中使用 pthreads 填充缓冲区。

注意客户端将其内容写入外部服务器地址(不是我的),服务器从外部客户端读取其内容。我在下面放的客户端和服务器之间没有相互通信。

缓冲区有两种填充方式:

  1. 服务器读取消息并将其放入缓冲区
  2. 客户端创建一条消息并将其放入缓冲区

这里是客户端函数:

void *client(void *threadid)
{
  //CLIENT INITIALIZATION AND CONNECT TO SERVER PROPERLY
  //sleep(1);   //sleep 1 second before you send again
  char *buff = "message1";   //message1,2,3 etc is defined by a random function

  pthread_mutex_lock(&lock);

  write(sockfd, buff, strlen(buff)+1);

  buffer_fill(buff);
  pthread_mutex_unlock(&lock);
  }
  pthread_exit(NULL);
 }

这里是服务器函数服务器从与我运行相同客户端代码的外部设备读取:

void *server(void *threadid)
{
  //SERVER INITIALIZATION USING THE PROPER PORT AND ADDRESS
  pthread_mutex_lock(&lock);
  bzero(buff, MAX_LENGTH);
  // read the message from client and copy it in buffer
  while(strlen(buff) == 0){
    read(sockfd, buff, sizeof(buff));
  }
  buffer_fill(buff);
  pthread_mutex_unlock(&lock);
  }
  pthread_exit(NULL);
}

我在 main 函数中使用简单的 pthread 初始化。所以我通过线程调用每个函数:

int main(int argc, char **argv)
{

  pthread_t threads[NUM_THREADS];
  int rc[NUM_THREADS];
  long t;

  for(t=0; t<NUM_THREADS; t++){

    //initiallize thread
    if (pthread_mutex_init(&lock, NULL) != 0)
    {
        printf("\n mutex init failed\n");
        return 1;
    }


    //create each thread according to value of t
    if(t==0){
      rc[t] = pthread_create(&threads[t], NULL, server, (void *)t);
    }else if(t==1){
      rc[t] = pthread_create(&threads[t], NULL, client, (void *)t);
    }

  }

  pthread_join(tid[0], NULL);
  pthread_join(tid[1], NULL);
  pthread_mutex_destroy(&lock);

  /* Last thing that main() should do */
  pthread_exit(NULL);

  return 0;
}

我假设问题出在(非常简单的)buffer_fill(char *message) 与线程结合使用的某个地方(注意:msg 是一个初始化为主外部零, int msg = 0):

void buffer_fill(char *m){

  if (msg<=MAX_MESSAGES){
    buffer[msg] = m;
    msg ++;
  }
  print_buffer();
}

当我连续执行这段代码时,我得到了这样的结果:

first print:
message2

second print:
message1
message1

third print:
message5
message5
message5

等等。

为什么消息是这样打印的,而不是连续打印的?我希望客户端将要写入的每条随机消息和服务器读取的每条消息都像这样一个接一个地堆叠在缓冲区中:

first print:
message2

second print:
message2
message1

third print:
message2
message1
message5

你的问题发生在这里

void buffer_fill(char *m){

  if (msg<=MAX_MESSAGES){
    buffer[msg] = m; // where
    msg ++;
  }
  print_buffer();
}

您应该使用 strcpy 或使用循环将值从 m 复制到 buffer

编辑:char * <=> const char * 您应该创建一个数组或动态分配缓冲区。