0

How is it possible to send data from one running thread to another running thread in c language. I want to generate data in main thread and send this data via a loop to another thread during each round trip of this loop.

// main 
int j = 0;    //initialize from 0
while (1) {
    pthread_mutex_lock(&mutex[1]);

    while (!flag[1])
        pthread_cond_wait(&cond[1], &mutex[1]);

    j++;
    if (j > 12)
        break;

    data[0] = orders[j];
    data[1] = j;
    thread_data_array[1].kilometer = data[0];
    thread_data_array[1].orders_num = data[1];
    pthread_mutex_unlock(&mutex[1]);

    if (j == 1) {
        thread_data_array[1].th_num = 1;
        pthread_create(&thread[1], NULL, threads, (void *) &thread_data_array[1]);
    }    
}

// another thread

data_th1 = (struct data_thread *) arg;

new_kilometer1 = data_th1->kilometer;
order_num1 = data_th1->orders_num;
num_th = data_th1->th_num;

//print results

But I will get only the first value of round trip.

Mathieu
  • 8,840
  • 7
  • 32
  • 45
S.far
  • 1
  • 1
  • 3
    Possible duplicate of [Passing Data between thread using C issue](http://stackoverflow.com/questions/13741243/passing-data-between-thread-using-c-issue) – Bidisha Pyne Feb 17 '17 at 12:35
  • Thanks for your suggestion, but I need to get a confirm signal from another thread then generate new data in main thread and pass this data to aforementioned thread.Your suggestion generate data first then pass all this data to second thread. – S.far Feb 17 '17 at 12:59
  • Proper approach is to create data in one thread and then pass it to another using signal info or queue. – unalignedmemoryaccess Feb 17 '17 at 13:27
  • can you give me more details please? – S.far Feb 17 '17 at 13:38
  • You want to be using a pipe in C. Among other places, look here: http://tldp.org/LDP/lpg/node11.html – Scott Mermelstein Feb 17 '17 at 22:16
  • You could use a `pipe` or you could use file global memory and mutex. If the data is always the same size, a unnamed pipe would work very well. – user3629249 Feb 18 '17 at 16:10
  • the posted code is always placing the data into the same (second) location in the array of `struct data_thread` array Suggest eliminate the array, so only have a single instance of the struct data_thread, then use the mutex to control access to a flag that indicates when the struct has a new/unconsumed data – user3629249 Feb 18 '17 at 16:17
  • the question is about a runtime problem. Such problems, to get any complete answers, must include the actual input, the actual output, the expected output, and short code that cleanly compiles. The posted code does not compile, is missing several data definitions, etc. – user3629249 Feb 18 '17 at 16:19
  • @S.far - I voted to leave this question open, but... I think you need to add the additional details to your question, like the detail about only one message is passed. Otherwise, the question as written begs for the dup. – jww Feb 18 '17 at 21:06

0 Answers0