Hi,
so now i am playing around with threading. I have written a peace of code to thread a process into two threads. each thread working with a different variable type. However this seam to me too c-ish. so I was wondering is there a better way to do this? Is it possible to write down only one template function for printing instead of print_32 and print_64?
Code:
#include <iostream>
#include <stdlib.h>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 2
struct t{
int id;
char *string;
};
struct z{
long long id;
char *string;
};
void *print_32(void *st){
int i;
t *my_data;
my_data = (struct t *) st;
sleep(my_data->id+my_data->id);
cout << "Thread with id : " << my_data->id << "\t"<< my_data->string<<" ...exiting " << endl;
pthread_exit(NULL);
}
void *print_64(void *st){
int i;
z *my_data;
my_data = (struct z *) st;
sleep(my_data->id+my_data->id);
cout << "Thread with id : " << my_data->id << "\t"<< my_data->string<<" ...exiting " << endl;
pthread_exit(NULL);
}
int main ()
{
int rc;
int i;
pthread_t threads[NUM_THREADS];
pthread_attr_t attr;
t in;
z in2;
void *status;
in.id = 2;
in.string = "string 21\n";
in2.id = 6;
in2.string = "string 61\n";
// Initialize and set thread joinable
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
cout << "main() : creating thread, " << 0 << endl;
rc = pthread_create(&threads[0], NULL, print_32, &in);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
cout << "main() : creating thread, " << 1 << endl;
rc = pthread_create(&threads[1], NULL, print_64, &in2);
if (rc){
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
// free attribute and wait for the other threads
pthread_attr_destroy(&attr);
for( i=0; i < NUM_THREADS; i++ ){
rc = pthread_join(threads[i], &status);
if (rc){
cout << "Error:unable to join," << rc << endl;
exit(-1);
}
cout << "Main: completed thread id :" << i ;
cout << " exiting with status :" << status << endl;
}
cout << "Done" << endl;
pthread_exit(NULL);
}
Thank you
baxy