#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);
}
}
}
我在创建和加入线程时遇到了麻烦。我也不确定如何通过引用传递线程参数的语法。代码应该在创建线程时打印以及它在线程例程中休眠多长时间。