关于 pthread_create 传参的疑问

文章讨论了在C语言中使用pthread_create创建线程时,参数arg的传递问题,特别是在将&thread_id作为arg时,新线程如何访问并打印这个值。作者通过示例和GDB调试确认了参数已成功传递给新线程。
摘要由CSDN通过智能技术生成

        对于函数原型 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 no
	  longer 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 也是有值 了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值