#include <iostream>

#include <pthread.h>

#include <vector>

#include <numeric>

#include <unistd.h>

using namespace std;


pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;


void* sum(void* data){

   vector<int>& p = *(vector<int>*)data;

   while(true){

// sleep(5);

       pthread_mutex_lock(&mutex);

       cout << "sum lock" << endl;

if(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(){

   vector<int> data;

   pthread_t tid;

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


   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);

}