Let's get straight to business. You need to understand the pthread APIs we'll discuss to get your hands dirty. To start with, this function is used to create a new thread:
#include <pthread.h>
int pthread_create(
pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine)(void*),
void *arg
)
The following table briefly explains the arguments used in the preceding function:
|
API arguments |
Comments |
|
pthread_t *thread |
Thread handle pointer |
|
pthread_attr_t *attr |
Thread attribute |
|
void *(*start_routine)(void*) |
Thread function pointer |
|
void * arg |
Thread argument |
This function blocks the caller thread until the thread passed in the first argument exits, as shown in the code:
int pthread_join ( pthread_t *thread, void **retval )
The following table briefly describes the arguments in the preceding function:
|
API arguments |
Comments |
|
pthread_t thread |
Thread handle |
|
void **retval |
Output parameter that indicates the exit code of the thread procedure |
The ensuing function should be used within the thread context. Here, retval is the exit code of the thread that indicates the exit code of the thread that invoked this function:
int pthread_exit ( void *retval )
Here's the argument used in this function:
|
API argument |
Comment |
|
void *retval |
The exit code of the thread procedure |
The following function returns the thread ID:
pthread_t pthread_self(void)
Let's write our first multithreaded application:
#include <pthread.h>
#include <iostream>
using namespace std;
void* threadProc ( void *param ) {
for (int count=0; count<3; ++count)
cout << "Message " << count << " from " << pthread_self()
<< endl;
pthread_exit(0);
}
int main() {
pthread_t thread1, thread2, thread3;
pthread_create ( &thread1, NULL, threadProc, NULL );
pthread_create ( &thread2, NULL, threadProc, NULL );
pthread_create ( &thread3, NULL, threadProc, NULL );
pthread_join( thread1, NULL );
pthread_join( thread2, NULL );
pthread_join( thread3, NULL );
return 0;
}