Example: Starting a thread in a Pthread program
This example shows how to start and pass parameters to a thread in a Pthread program.
Note: By using the code examples, you agree to the terms of the Code license and disclaimer information.
/*
Filename: ATEST11.QCSRC
The output of this example is as follows:
Enter Testcase - LIBRARY/ATEST11
Create/start a thread with parameters
Wait for the thread to complete
Thread ID 0000000c, Parameters: 42 is the answer to "Life, the Universe and Everything"
Main completed
*/
#define _MULTI_THREADED
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define checkResults(string, val) { \
if (val) { \
printf("Failed with %d at %s", val, string); \
exit(1); \
} \
}
typedef struct {
int threadParm1;
char threadParm2[124];
} threadParm_t;
void *theThread(void *parm)
{
pthread_id_np_t tid;
threadParm_t *p = (threadParm_t *)parm;
tid = pthread_getthreadid_np();
printf("Thread ID %.8x, Parameters: %d is the answer to \"%s\"\n",
tid.intId.lo, p->threadParm1, p->threadParm2);
return NULL;
}
int main(int argc, char **argv)
{
pthread_t thread;
int rc=0;
threadParm_t *threadParm;
printf("Enter Testcase - %s\n", argv[0]);
threadParm = (threadParm_t *)malloc(sizeof(threadParm));
threadParm->threadParm1 = 42;
strcpy(threadParm->threadParm2, "Life, the Universe and Everything");
printf("Create/start a thread with parameters\n");
rc = pthread_create(&thread, NULL, theThread, threadParm);
checkResults("pthread_create()\n", rc);
printf("Wait for the thread to complete\n");
rc = pthread_join(thread, NULL);
checkResults("pthread_join()\n", rc);
printf("Main completed\n");
return 0;
}