#include "sopnamsp.h"
#include "zthread.h"
#include "resusage.h"

#include <iostream>
#include <vector>

#include "tmatrix.h"
#include "tarrinit.h"

#include <stdlib.h>
#include <stdio.h>

/* -------------------------------------------------
  Programme de test des classes de threads de SOPHYA
  SOPHYA::ZThread SOPHYA::ZMutex ...
  Exemples d'execution
  csh> time zthr mtx 2 500
  csh> time zthr arr 2 500
*/
 
#include <time.h>
#include <unistd.h>

#include "timing.h"


// --- Structure d'argument pour fonction d'execution dans les threads de test
typedef struct  {
  int thid;
  int M;
} ztarg;

// --- fonction de test simple avec boucle de sleep
void funzt(void *arg)
{
time_t t0, t1;
int i;

ztarg * za = (ztarg *)arg;

t0 = time(NULL);
printf("+++++ funzt(ThId=%d) Entry to funzt (za.M=%d) +++++\n", za->thid, za->M);
int imax = za->M;
for(i=0; i<imax; i++)
  {
  sleep(3);
  t1 = time(NULL)-t0;
  printf("++funzt(ThId=%d)  Dt= %d \n", za->thid, (int)t1);
  }

return;
}

// --- fonction de test simple avec calcul matriciel
void mtx_funzt(void *arg)
{
  ztarg * za = (ztarg *)arg;
  cout << ">>>> mtx-funzt(ThId=" << za->thid << ") - Matrix size= " << za->M << endl;
  
  sa_size_t m = za->M;
  Matrix a1(m,m), a2(m,m), mxprod; 
  a1 = RandomSequence(RandomSequence::Gaussian, 0., 4.);
  a2 = RandomSequence(RandomSequence::Gaussian, 0., 3.);
  char buff[128];
  sprintf(buff, "mtx-funzt(ThId=%d) EndOfInit", za->thid); 
  PrtTim(buff);
  mxprod = a1*a2;
  sprintf(buff, "mtx-funzt(ThId=%d) EndOfMxProd", za->thid); 
  PrtTim(buff);
  return;
}
// --- fonction de test simple avec calcul matriciel
void arr_funzt(void *arg)
{
  ztarg * za = (ztarg *)arg;
  cout << ">>>> arr-funzt(ThId=" << za->thid << ") - Matrix size= " << za->M << endl;
  
  sa_size_t m = za->M;
  TMatrix<int_4> a1(m,m), a2(m,m), ares; 
  a1 = RegularSequence(1.,1.);
  a2 = RegularSequence(5.,3.);
  char buff[128];
  sprintf(buff, "arr-funzt(ThId=%d) EndOfInit", za->thid); 
  PrtTim(buff);
  ares = 4*a1*12*a2;
  sprintf(buff, "arr-funzt(ThId=%d) EndOfOper", za->thid); 
  PrtTim(buff);
  return;
}



class CountLock : public ZMutex {
  int count;
public:
  CountLock() { count = 0; }
  inline int Count() { lock(); int rc = ++count; unlock(); return(rc); 
  }
};


static int N = 1;
static int M = 5;

int main(int narg, char *arg[])

{

  if (narg < 4) {
    cout << " Usage: zthr select N LM" << endl;
    cout << "  select= sl -> simple loop with sleep " << endl;
    cout << "  select= mtx -> matrix init and multiply mx1*mx2" << endl;
    cout << "  select= arr -> array/matrix init and operation c1*a1+c2*a2 " << endl;
    cout << "  select= clk -> Mutex lock count  " << endl;
    cout << "  N= Number of threads (sl/mtx) or CountLock " << endl;
    cout << "  LM = Loop limit (sl) or Matrix size (mtx) " << endl;
    return(1);
  }

  string sel = arg[1];
  if ((sel != "sl") && (sel != "mtx") && (sel != "arr") && (sel != "clk")) {
    cout << "zthr/erreur argument sel (!= sl / mtx / arr / clk) " << endl;
    return 2;
  }

  //--  Decodage arguments
  N = atoi(arg[2]);
  M = atoi(arg[3]);
  cout << "zthr/Info: select=" << sel << " N=" << N << " M= " << M << endl;
 
  
  InitTim();
  SophyaInit();

  int rc = 0;
  try {
    ResourceUsage res;
    if ((sel == "mtx") || (sel == "arr") || (sel == "sl")) {
      vector<ztarg *> vza;
      vector<ZThread *> vzth;
      for(int i=0; i<N; i++) {
	cout << "*****zthr: Creating Thread " << i+1 << " /" << N << endl;
	ZThread * pzt = new ZThread();
	ztarg* zap = new ztarg;
	vzth.push_back(pzt);
	zap->thid = i+1;  zap->M = M;
	vza.push_back(zap);
	if (sel == "mtx")  pzt->setAction(mtx_funzt, vza[i]);
	else if (sel == "arr")  pzt->setAction(arr_funzt, vza[i]);
	else pzt->setAction(funzt, vza[i]);
      }
      cout << "***zthr: Starting threads ... " << endl;
      PrtTim("***zthr/StarThr");
      for(int i=0; i<N; i++) vzth[i]->start();
      sleep(1);
      cout << "***ResourceUsage before thr[i].join()" << endl;
      cout << res;
      cout << "***zthr Joining Threads ..." << endl;
      for(int i=0; i<N; i++) vzth[i]->join();
      cout << "***zthr Threads Z1 ... Z" << N << " Finished OK" << endl;
      cout << res;
      for(int i=0; i<N; i++) {
	delete vzth[i];
	delete vza[i];
      }
    }
    else {
      PrtTim("BeginOfCount");
      CountLock clk;
      int kk;
      for(kk=0; kk<atoi(arg[3]); kk++) {
	clk.Count();
      }
      cout << " End CountLock-Test Count= " << clk.Count() << endl;
    }
  }
  catch (PThrowable exc) {
    cerr << "zthr: catched Exception " << exc.Msg() << endl;
    rc = 77;
  }  
  catch (...) {
    cerr << " catched unknown (...) exception (lpk.cc) " << endl; 
    rc = 78; 
  } 
  
  return(rc);
  
}



