Thursday, October 20, 2011

Multithreading in C in Different CPU core

# define _GNU_SOURCE
# include <stdio.h>
# include <math.h>
# include <stdlib.h>
# include <pthread.h>
# include <stdlib.h>

pthread_mutex_t mux = PTHREAD_MUTEX_INITIALIZER;


struct p2p{
int st;
int en;
};

void *primeChk(void* val);

int main()
{
  pthread_t thread1,thread2,thread3,thread4;
  struct p2p valu1,valu2,valu3,valu4;
  int j,ret1,ret2,ret3,ret4;
  cpu_set_t cpuset;

// pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset);


  valu1.st = 1;
  valu1.en = 5000;
  valu2.st = 5001;
  valu2.en = 10000;
  valu3.st = 10001;
  valu3.en = 15000;
  valu4.st = 15001;
  valu4.en = 20000;

   // initialization
   CPU_ZERO(&cpuset);


   CPU_SET(0,&cpuset);
   pthread_setaffinity_np(thread1, sizeof(cpu_set_t), &cpuset);
   ret1 = pthread_create(&thread1,NULL,&primeChk,(void*)&valu1);
   //CPU_ZERO(&cpuset); 

   CPU_SET(1,&cpuset);
   pthread_setaffinity_np(thread2, sizeof(cpu_set_t), &cpuset);
   ret2 = pthread_create(&thread2,NULL,&primeChk,(void*)&valu2);
  // CPU_ZERO(&cpuset);
/*      
    CPU_SET(2,&cpuset);
    pthread_setaffinity_np(thread3, sizeof(cpu_set_t), &cpuset);
    ret3 = pthread_create(&thread3,NULL,&primeChk,(void*)&valu3);
   
   CPU_SET(3,&cpuset);
   pthread_setaffinity_np(thread4, sizeof(cpu_set_t), &cpuset);
   ret4 = pthread_create(&thread4,NULL,&primeChk,(void*)&valu4);
  */

  pthread_join(thread1,NULL);
  pthread_join(thread2,NULL);
 // pthread_join(thread3,NULL);
 // pthread_join(thread4,NULL);

  return 0;
}


void *primeChk(void *val)
{
  struct p2p *valu = (struct p2p *)val;
  int str,end,i,k,j,l,m;

 // pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
  str = valu->st;
  end = valu->en;
  if(str == 1)
  printf("%d",++str);

  pthread_mutex_lock(&mux);
  for(i=str;i<=end;i++)
  {
     k = sqrt(i);l = 0;
     for(j=2;j<=k+1;j++)
     if(i % j == 0)
     {
        l = 1;break;
     }
     if(l == 0)printf(" %d",i);
  }
  pthread_mutex_unlock(&mux);

  //pthread_getaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset);
 // printf("\nSet returned by pthread_getaffinity_np() contained:\n");
 // for (j = 0; j < CPU_SETSIZE; j++)
   //    if (CPU_ISSET(j, &cpuset))
    //   printf("    CPU %d\n", j);


}

No comments:

Post a Comment

How to enable hotspot in TPG iPhone

 By default, the hotspot does not work on the phone. It will ask you to contact the provider. This video will help you bypass the network ...