在示例 2–1 中,一个线程执行位于顶部的过程,该过程首先创建一个辅助线程来执行 fetch() 过程。fetch() 执行复杂的数据库查找操作,查找过程需要花费一些时间。
主线程将等待查找结果,但同时还执行其他操作。因此,主线程将执行其他活动,然后通过执行 pthread_join() 等待辅助线程。
将新线程的 pbe 参数作为栈参数进行传递。这个线程参数之所以能够作为栈参数传递,是因为主线程会等待辅助线程终止。不过,首选方法是使用 malloc 从堆分配存储,而不是传递指向线程栈存储的地址。如果将该参数作为地址传递到线程栈存储,则该地址可能无效或者在线程终止时会被重新分配。
void mainline (...)
{
struct phonebookentry *pbe;
pthread_attr_t tattr;
pthread_t helper;
void *status;
pthread_create(&helper, NULL, fetch, &pbe);
/* do something else for a while */
pthread_join(helper, &status);
/* it's now safe to use result */
}
void *fetch(struct phonebookentry *arg)
{
struct phonebookentry *npbe;
/* fetch value from a database */
npbe = search (prog_name)
if (npbe != NULL)
*arg = *npbe;
pthread_exit(0);
}
struct phonebookentry {
char name[64];
char phonenumber[32];
char flags[16];
}