#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
const int kMaxThreads = 10;
void * threadRoutine(void * threadArg) {
int myThreadNumber = * ((int * ) threadArg);
//(int)threadArg
printf("threadRoutine()=>: this is thread number %d!\n", myThreadNumber);
int sleepTime = random() % 20;
sleep(sleepTime);
printf("threadRoutine()=>: thread[%d] completed after sleeping %d [secs]!\n",
myThreadNumber, sleepTime);
pthread_exit((void * ) myThreadNumber);
}
int main(int argc, char * argv[]) {
pthread_t threads[kMaxThreads];
printf("main()=>: creating threads...\n");
for (int jj = 0; jj < kMaxThreads; jj++) {
if (pthread_create( & threads[jj], NULL, threadRoutine, (void * ) jj) != 0) {
/* undefined reference to a pthread_create*/
} else {
printf("main()=>: created thread[%d]!\n", jj);
}
}
printf("main()=>: waiting for threads to complete...\n");
for (int jk = 0; jk < kMaxThreads; jk++) {
void * currentThread;
if (pthread_join(threads[jk], & currentThread) != 0) {
/* undefined reference to a pthread_join*/
} else {
printf("main()=>: completed thread[%d]!\n", (int) currentThread);
}
}
}
I am having trouble, with creating and join a thread. I am also not sure about the syntax of how to pass a thread parameter by reference. code should print when a thread is created and how long it sleeps in thread routine.