/* standard I/O routines */
#i nclude /* pthread functions and data structures */
/* function to be executed by the new thread */
void*
do_loop(void* data)
{
int i; /* counter, to print numbers */
int j; /* counter, for delay */
int me = *((int*)data); /* thread identifying number */
for (i=0; i<10; i++) {
for (j=0; j<500000; j++) /* delay loop */
;
printf("'%d' - Got '%d'\n", me, i);
}
/* terminate the thread */
pthread_exit(NULL);
}
/* like any C program, program's execution begins in main */
int
main(int argc, char* argv[])
{
int thr_id; /* thread ID for the newly created thread */
pthread_t p_thread; /* thread's structure */
int a = 1; /* thread 1 identifying number */
int b = 2; /* thread 2 identifying number */
/* create a new thread that will execute 'do_loop()' */
thr_id = pthread_create(&p_thread, NULL, do_loop, (void*)&a);
/* run 'do_loop()' in the main thread as well */
do_loop((void*)&b);
/* NOT REACHED */
return 0;
}
注:pthread_create()在pthread.h中的描述为:
extern int pthread_create (pthread_t *__restrict __threadp,
__const pthread_attr_t *__restrict __attr,
void *(*__start_routine) (void *),
void *__restrict __arg) __THROW;
函数有四个参数,第一个为pthread_t结构指针,用来存放线程的相关信息,第二个参数用来设置线程的相关属性,第三个参数用来指定CallBack函数,第四个参数用来传递参数.
线程的CallBack函数应该是一个返回值为void的指针,并且参数也为void指针.我个人感觉这就像C#中的object的装箱与拆箱,把对象封装后传递.