0
void *interpretWrapper(void* arg) {
    char* res = (char*) arg;
    cout << res[0] << endl;
}

void *recvConn(void * data) {
    char buffer[1024];
    int buffer_len = 1024;
    while(true) {
        memset(buffer, 0, buffer_len);

        if((bytecount = recv(*csock, buffer, buffer_len, 0)) == -1)  {
        printf("yalehwyyy\n");
        fprintf(stderr, "Error receiving data %d\n", errno);
        printf("%d", csock);
        break;
        }else if (bytecount == 0) {
            fprintf(stderr, "Socket Closed ! Robotino needs to reconnect !!\n");
            break;
        }

      pthread_t thread_id = 0;
      pthread_create(&thread_id, NULL, interpretWrapper, &buffer);
      pthread_detach(thread_id);
      printf("Received bytes %d\nReceived string \"%s\"\n", bytecount, buffer);
   }
}

In the above code, whenever I receive a string, which is placed into buffer, I print the string in recvConn and the result is in fact the sent string. However, once the string is passed to interpretWrapper, all I get when I print res[0] is an empty char, whereas the expected output would be the first char of the sent string. I also tried using strings, and also got an empty string.

Moreover, I tried sending an integer, whereas printing the integer inside interpretWrapper produced the passed integer correctly. I have been trying to figure it out for two days now, what seems to be the problem?

BitRiver
  • 291
  • 3
  • 11

2 Answers2

2

The parent thread and child are racing: parent is continuing the while loop and hitting memset(buffer, 0, buffer_len) before the child thread looks at the buffer. You probably want to pass a copy to the child thread.

Casey
  • 41,449
  • 7
  • 95
  • 125
  • And how can I pass a copy instead of a reference to the array? – BitRiver Jun 18 '13 at 14:44
  • malloc a new buffer, copy the received contents into and pass this new buffer pointer to your thread, let the thread read it and then have that thread free the buffer is one way. A better way would be to use a thread safe queue. http://stackoverflow.com/questions/4577961/pthread-synchronized-blocking-queue and http://stackoverflow.com/questions/2893713/pthread-queue-system may be helpful :) – Jimbo Jun 18 '13 at 14:48
  • @BitRiver I would probably allocate a fresh buffer for each `recv`, and pass ownership to the new thread - at least until profiling shows allocation to be a bottleneck. – Casey Jun 18 '13 at 14:50
  • @Yakk - OK a new BufferClass instance, then :) – Martin James Jun 19 '13 at 10:17
0

Send a copy of buffer, because it's pointer will be changed when looping !

Yacine Hebbal
  • 394
  • 3
  • 16