Joining and Detaching Threads
#include
#include
#include
#include
#include
using namespace std;
#define num_threads 5
void *wait(void *t)
{
int i;
long tid;
tid = (long)t;
sleep(1);
cout << "Sleeping in thread " << endl;
cout << "Thread with id : " << tid << " ...exiting " << endl;
pthread_exit(NULL);
}
int main ()
{
int rc;
int i;
pthread_t threads[num_threads];
pthread_attr_t attr;
void *status;
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, pthread_create_joinable);
for( i=0; i < num_threads; i++ )
{
cout << "main() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], NULL, wait, (void *)i );
if (rc)
{
cout << "Error:unable to create thread," << rc << endl;
exit(-1);
}
}
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 << "Main: program exiting." << endl;
pthread_exit(NULL);
}
Output
main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Sleeping in thread
Thread with id : 0 .... exiting
Sleeping in thread
Thread with id : 1 .... exiting
Sleeping in thread
Thread with id : 2 .... exiting
Sleeping in thread
Thread with id : 3 .... exiting
Sleeping in thread
Thread with id : 4 .... exiting
Main: completed thread id :0 exiting with status :0
Main: completed thread id :1 exiting with status :0
Main: completed thread id :2 exiting with status :0
Main: completed thread id :3 exiting with status :0
Main: completed thread id :4 exiting with status :0
Main: program exiting.
Conditional Compilation
#include
#include
using namespace std;
#define debug
#define min(a,b) (((a)<(b)) ? a : b)
int main ()
{
int i, j;
i = 100;
j = 30;
#ifdef debug
cerr <<"Trace: Inside main function" << endl;
#endif
#if 0
cout << Mkstr(Hello C++) << endl;
#endif
cout <<"The minimum is " << Min(i, j) << endl;
#ifdef debug
cerr <<"Trace: Coming out of main function" << endl;
#endif
return 0;
}
Output
Trace: Inside main function
The minimum is 30
Trace: Coming out of main function
No comments:
Post a Comment