LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   send parameter from thread to thread (https://www.linuxquestions.org/questions/programming-9/send-parameter-from-thread-to-thread-90237/)

marek 09-07-2003 02:31 PM

send parameter from thread to thread
 
As is written in this title, i would like to send data from one thread to second by the parameter of first thread. So it should looks like this:

void * my_thread1(void *my_parameter)
{
int statement = 1;
return (void *)statement
}

main (..)
{
int local_value;
pthread_create(thread_ID,..., my_thread1,....);
//I wait as thread my_thread1 will be finished
pthread_join(&thread_ID, (void *)&local_value);
printf("That's data received from my_thread1 = %d, local_value)
}


This is a part of my program which i am interested a lot, could you help me?? (where is the error and what about sending data like float char and double????)

eric.r.turner 09-07-2003 05:41 PM

The problem is how you are returning your value. pthread_join really wants the address of a pointer. Allocate the memory in your thread function, then return the address of that memory. Here's a similar example that works:

Code:

#include <stdio.h>
#include <stdlib.h>    /* for abort    */
#include <string.h>    /* for strerror */
#include <pthread.h>

void* threadFunction(void* arg)
{
  int* statement;
  statement = calloc(1, sizeof(int));
  *statement = 1;
  return(statement);
}

int main( int argc, char* argv[] )
{
  pthread_t threadId;
  int*      threadResult;
  int      threadStatus;

  threadStatus = pthread_create(&threadId,
                                NULL,
                                threadFunction,
                                NULL);

  if(threadStatus != 0) {
      fprintf(stderr,
              "pthread_create failed: %s\n",
              strerror(threadStatus));
      abort();
  }

  threadStatus = pthread_join(threadId,
                              (void**)&threadResult);

  if(threadStatus != 0) {
      fprintf(stderr,
              "pthread_join failed: %s\n",
              strerror(threadStatus));
      abort();
  }

  printf("Data received from threadFunction: %d\n", *threadResult);

  free(threadResult);

  return(0);
}

To compile it, use:

Code:

gcc -Wall -o testthread testthread.c -lpthread

marek 09-08-2003 05:33 AM

So your program works perfectly (but i used little different statement in thread fuction ThreadFunction ->
return *statement instead return(statement)

What about my program it also work great but i forgot to delete one line pthread_exit which i had in my thread function :D (God punish us for stupidity), without this line it works like it should, sending data from one thread to second

Thanks eric for help


All times are GMT -5. The time now is 12:50 AM.