Multithreading C++
Multithreading C++
Creating Threads
The following routine is used to create a POSIX thread −
#include <pthread.h>
pthread_create (thread, attr, start_routine, arg)
Terminating Threads
There is following routine which we use to terminate a POSIX
thread −
#include <pthread.h>
pthread_exit (status)
Example
This simple example code creates 5 threads with the
pthread_create() routine.
#define NUM_THREADS 5
int main () {
pthread_t threads[NUM_THREADS];
int rc;
int i;
for( i = 0; i < NUM_THREADS; i++ ) {
cout << "main() : creating thread, "
<< i << endl;
rc = pthread_create(&threads[i],
NULL, PrintHello, (void *)i);
if (rc) {
cout << "Error:unable to create
thread," << rc << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
#define NUM_THREADS 5
struct thread_data {
int thread_id;
char *message;
};
pthread_exit(NULL);
}
int main () {
pthread_t threads[NUM_THREADS];
struct thread_data td[NUM_THREADS];
int rc;
int i;
#define NUM_THREADS 5
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;