#include <iostream>

#include <pthread.h>

#include <vector>

#include <numeric>

#include <unistd.h>

using namespace std;


struct Data{

   vector<int>& data;

   pthread_mutex_t& mutex;

   pthread_cond_t& cond;

};


void* sum(void* data){

   auto& p = ((Data*)data)->data;

   auto& mutex = ((Data*)data)->mutex;

   auto& cond = ((Data*)data)->cond;

 

  // auto [&p,&mutex,&cond] = *(Data*)data;

   while(true){

// sleep(5);

       pthread_mutex_lock(&mutex);

       cout << "sum lock" << endl;

while(p.size()<5) {

           cout << "sum before wait" << endl;

    pthread_cond_wait(&cond,&mutex); // unlock/lock

           cout << "sum after wait" << endl;

}

    cout << "sum:" << accumulate(p.begin(),p.end(),0) << endl;

p.clear();

       pthread_mutex_unlock(&mutex);

       cout << "sum unlock" << endl;

   }

}



int main(){

   pthread_mutex_t mutex;// = PTHREAD_MUTEX_INITIALIZER;

   pthread_cond_t cond;// = PTHREAD_COND_INITIALIZER;

   pthread_mutex_init(&mutex,NULL);

   pthread_cond_init(&cond,NULL);


   vector<int> data;

   pthread_t tid;

   Data d = {data,mutex,cond};

   pthread_create(&tid,NULL,sum,&d);


   int n;

   while(cin >> n){

      pthread_mutex_lock(&mutex);

      cout << "main lock" << endl;

      data.push_back(n);

      if(data.size()>=5) {

  pthread_cond_signal(&cond);

         cout << "main signal" << endl;

      }

      pthread_mutex_unlock(&mutex);

      cout << "main unlock" << endl;


   }

   

   pthread_join(tid,NULL);

   pthread_mutex_destroy(&mutex);

   pthread_cond_destroy(&cond);

}