对于函数原型 int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg) 里的参数 arg,之前一直有疑问,就是把 &thread 传给 arg时,新创建的线程里是否能取到这个值呢?看例子:
#include <pthread.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <ctype.h>#define handle_error_en(en, msg) \do { errno = en; perror(msg); exit(EXIT_FAILURE); } while (0)#define handle_error(msg) \do { perror(msg); exit(EXIT_FAILURE); } while (0)static void *thread_start(void *arg)
{ size_t stack_size = 0;pthread_attr_t attr;printf("in child thread id: %lu\n", *((pthread_t*)arg));int ret = pthread_getattr_np(pthread_self(), &attr);if(ret != 0){handle_error_en(ret, "pthread_attr_init");}ret = pthread_attr_getstacksize(&attr, &stack_size);if (ret != 0){handle_error_en(ret, "pthread_attr_setstacksize");}printf("current thread stack_size = %lu\n", stack_size);sleep(200);return 0;
}void (*cancel_hook) (void *);
int main(int argc, char *argv[])
{int s, tnum, opt, num_threads;pthread_t thread_id;pthread_attr_t attr;int stack_size = 0x80000;void *res;printf("pid of a.out %lu\n", getpid());printf("sizeof(pthread_mutex_t) = %lu\n", sizeof(pthread_mutex_t));printf("pointer of function = %lu\n", sizeof(cancel_hook));/* Initialize thread creation attributes */s = pthread_attr_init(&attr);if (s != 0){handle_error_en(s, "pthread_attr_init");} if (stack_size > 0) {s = pthread_attr_setstacksize(&attr, stack_size);if (s != 0){handle_error_en(s, "pthread_attr_setstacksize");}}printf("set stack size %lu\n", stack_size);s = pthread_create(&thread_id, &attr, &thread_start, &thread_id);if (s != 0){handle_error_en(s, "pthread_create");}printf("the child threadId %lu\n", thread_id);/* Destroy the thread attributes object, since it is nolonger needed */s = pthread_attr_destroy(&attr);if (s != 0){handle_error_en(s, "pthread_attr_destroy");}s = pthread_join(thread_id, &res);if (s != 0){handle_error_en(s, "pthread_join");}exit(EXIT_SUCCESS);
}
新线程里打印了入参 arg 的值:printf("in child thread id: %lu\n", *((pthread_t*)arg)); 因为 arg 是 void* 类型,所以需要强转一下再解引用。
可以看到在 main 线程和子线程里打印出来的线程 id 是一样的,即在调用 pthread_create(&thread_id, &attr, &thread_start, &thread_id); 时,在新创建的线程里已经能取到 thread_id 的值。看源码片段:
在GDB 跟踪里可以看到,在调用 create_thread 前,已经把入参 arg 赋值给了 pd->arg,经过*newthread = (pthread_t)pd,此时 arg 已经有值了,即 pd->arg 也是有值 了。