How to Develop Linux Program To Cll A Method From Thread A Compiled File C++ Code Using Pthread_Create Posix Library

POSIX, UNIX, Linux, Programming

Linux Program To Cll A Method From Thread A Compiled File C++ Code Using Pthread_Create Posix Library

Part 1:

#include<pthread.h>
#include<iostream>

using namespace std;

void *thread_proc(void *arg){
cout<<“hello from thread\n”;
 

}
int main()
{
pthread_t tid1;
pthread_t tid2;
pthread_create(&tid1 , NULL ,thread_proc , (void *) 1);
pthread_create(&tid2 , NULL ,thread_proc , (void *) 2);
pthread_join(tid1 , NULL);
pthread_join(tid2 , NULL);
return 0;

}

Part 2:

#include<cstdlib>
#include<iostream>
#include<ctime>

 
/*

Serial times:  Parallel times
7.46             5.23
8.04             5.90
(and so on)      (and so on)
Average: 7.88    5.77

 */
struct task_args_t{
float *a, *b;
int num_elements;    

};
void smooth(float *a , int num_elements, float *b){
 
    
    
for(int j = 0 ; j< 100 ; j++){
int  i ;
 for(i=1 ; i< num_elements; i++)
       b[i] = (a[i] + a[i-1])/2.0;

    }
 
}

void *smooth_task(void *args){

task_args_t *targs = (task_args_t *) args;
smooth (targs->a,targs->num_elements, targs->b);

}

void *init_mat(float *a , int num_elements){

  int i;
  unsigned int seed;
 for (i=0 ; i < num_elements ; i++){

  a[i]  = static_cast<float>(rand_r(&seed))/rand_r(&seed);
        
}

}

void *init_mat_task(void *args){

  task_args_t *targs = (task_args_t *) args;
  init_mat (targs->a, targs->num_elements);

}
const int NUM_ELEMENTS = 50000000;
 
int main()
{
static float mat1[NUM_ELEMENTS],mat2[NUM_ELEMENTS];
pthread_t tid1 , tid2;
task_args_t args1 , args2;
srand(time(NULL));
args1.a = mat1;
args1.num_elements= NUM_ELEMENTS/2;
args1.b = mat2;

pthread_create(&tid1 , NULL , init_mat_task, (void *) &args1);
args2.a = mat1 + (NUM_ELEMENTS / 2);
args2.num_elements= NUM_ELEMENTS/2;
args2.b = mat2 + (NUM_ELEMENTS / 2);

pthread_create(&tid2 , NULL , init_mat_task, (void *) &args2);

pthread_join(tid1 , NULL);
pthread_join(tid2 , NULL);
pthread_create(&tid1 , NULL , smooth_task, (void *) &args1);
pthread_create(&tid2 , NULL , smooth_task, (void *) &args2);

pthread_join(tid1 , NULL);
pthread_join(tid2 , NULL);
return 0;

}

LEAVE A REPLY

Please enter your comment!
Please enter your name here