Ads

Sunday 6 April 2014

Object Oriented and Multi-core Programming Assignment Group C -1

#include<iostream>
#include<pthread.h>
#include<string>
#include<unistd.h>
#include<cstdlib>
#include<iomanip>
#include<sched.h>

using namespace std;




class threadClass
{
 pthread_t t1;
 
 public :
  //friend void function();
  void run();
  void join();
  void stick_thread(int coreid);
  pthread_t self();
  //virtual void *run(void) = 0;
};




class oddeve:public threadClass
 {
  int a[10],n;
  public:
  //void *run();
  void exchange(int,int);
  void compare(int,int);
  void oddEvenMerge(int,int,int);
  void oddEvenMergeSort(int,int);
  void getdata();
  void display();
 };

static void *function1(void *);
void *function1(void *arg)
{
 ((oddeve*)arg)->getdata();
}
/*
static void *function2(void *);
void *function2(void *arg)
{
 ((oddeve*)arg)->display();
}
*/

void threadClass::join()
{
 pthread_join(t1,NULL);
}


pthread_t threadClass::self()
{ 
 return t1;
}


void threadClass::stick_thread(int core_id)
{ 
 cpu_set_t cpuset;
 CPU_ZERO(&cpuset);
 CPU_SET(core_id, &cpuset);
 //pthread_t current_thread = pthread_self();    
 sched_setaffinity(getpid(), sizeof(cpu_set_t), &cpuset);
}


void threadClass::run()
{
 
 pthread_create(&t1,NULL,function1,this);
}

void oddeve::exchange(int i, int j) 
{
 int t = a[i];
 a[i] = a[j];
 a[j] = t;
}
 
void oddeve::compare(int i, int j) 
{
 if (a[i] > a[j])
  exchange(i, j);
}
 
/**
* lo is the starting position and
* n is the length of the piece to be merged,
* r is the distance of the elements to be compared
*/
void oddeve::oddEvenMerge(int lo, int n, int r) 
{
 int m = r * 2;
 if (m < n) 
 {
  oddEvenMerge(lo, n, m); // even subsequence
  oddEvenMerge(lo + r, n, m); // odd subsequence
  for (int i = lo + r; i + r < lo + n; i += m)
  compare(i, i + r);
 } 
 else
 compare(lo, lo + r);
}
 
/**
* sorts a piece of length n of the array
* starting at position lo
*/
void oddeve::oddEvenMergeSort(int lo, int n) 
{
 if (n > 1) 
 {
  int m = n / 2;
  oddEvenMergeSort(lo, m);
  oddEvenMergeSort(lo+m, m);
  oddEvenMerge(lo, n, 1);
 }
}
 
void oddeve::getdata()
{

 cout<<"\n\nCORE : "<<sched_getcpu();
 cout<<"\nTHREAD : "<<(long)self()<<"\n";
 cout<<"\nEnter no. of elements in array (n th power of 2) : ";
 cin>>n;
 cout<<"\nEnter array elements:";
 for (int i = 0; i < n; i++)
  cin>>a[i];
 
 oddEvenMergeSort(0, n);
 
} 

void oddeve::display()
{
 //cout<<"\n\nCORE : "<<sched_getcpu();
 cout<<"\nTHREAD ID: "<<(long)self()<<"\n";
 cout<<"\nSorted Array: ";
 for (int i = 0; i < n; i++)
  cout<<a[i]<<"\t";
 cout<<endl;
}
 


int main()
{
 oddeve *thread1=new oddeve;
 oddeve *thread2=new oddeve;
 //oddeve *thread1=new oddeve;
 thread1->stick_thread(0);
 thread1->run();
 sleep(20);
 
 

 thread2->stick_thread(1);
 thread2->run();
 sleep(20);
 thread1->display();
 thread2->display();
 pthread_exit(NULL);
 return 0;
}
 
 



No comments:

Post a Comment