在demo1的基础上,添加了传递参数给线程。这样可以更明显地看到,进程依次创建了线程,但是线程的执行顺序却是不固定的。
#include <stdio.h>
#include <pthread.h>
void *fn(void *arg)
{
printf("thread #%u : get arg=<%d>, my PID=%d\n", \
(unsigned int)pthread_self(), (int)arg, getpid());
return NULL;
}
int main(int argc, char *argv[])
{
pthread_t tid;
int error;
int i;
for(i=0; i<10; i++)
{
error = pthread_create( &tid, NULL, fn, (void*)i);
if(0 != error)
{
perror("pthead_create error");
return -1;
}
else
{
printf("main: my PID=%d, set arg=<%d>, create thread #%u OK!\n", \
getpid(), i, (unsigned int)tid);
}
}
sleep(3); /* give threads time to print out */
return 0;
}
main: my PID=3379, set arg=<0>, create thread #3075865408 OK!
main: my PID=3379, set arg=<1>, create thread #3067472704 OK!
main: my PID=3379, set arg=<2>, create thread #3059080000 OK!
main: my PID=3379, set arg=<3>, create thread #3050687296 OK!
main: my PID=3379, set arg=<4>, create thread #3042294592 OK!
main: my PID=3379, set arg=<5>, create thread #3033901888 OK!
main: my PID=3379, set arg=<6>, create thread #3025509184 OK!
main: my PID=3379, set arg=<7>, create thread #3017116480 OK!
main: my PID=3379, set arg=<8>, create thread #3008723776 OK!
main: my PID=3379, set arg=<9>, create thread #3000331072 OK!
thread #3025509184 : get arg=<6>, my PID=3379
thread #3033901888 : get arg=<5>, my PID=3379
thread #3042294592 : get arg=<4>, my PID=3379
thread #3017116480 : get arg=<7>, my PID=3379
thread #3050687296 : get arg=<3>, my PID=3379
thread #3008723776 : get arg=<8>, my PID=3379
thread #3059080000 : get arg=<2>, my PID=3379
thread #3000331072 : get arg=<9>, my PID=3379
thread #3075865408 : get arg=<0>, my PID=3379
thread #3067472704 : get arg=<1>, my PID=3379