pthread_create函数中的第四个参数 [英] The fourth parameter in pthread_create function

查看:735
本文介绍了pthread_create函数中的第四个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如下:

  int code = pthread_create(& d-> thread_id,& attr,QThreadPrivate: :start,this); 

其中 QThreadPrivate :: start 函数。



那么,第四个参数 this 如果替换为 NULL

pthread_create 的第四个参数传递给线程函数,并允许该函数根据该参数改变行为。



有关 pthread_create 的OpenGroup文档可以找到此处



在这种情况下,它只是传递指针到当前对象,假设 start 函数可以使用它来访问特定对象的成员变量。



如果你传递 NULL ,则创建的线程将获得 NULL ,并且将无法访问对象特定数据



你可能会认为,因为 QThreadPrivate :: start 是一个静态函数,它不能以任何方式访问非静态成员(因为它通常没有对象可以工作)。



但这只适用于隐式访问 - 没有什么阻止你通过显式的 这个指针访问对象数据,只要遵循访问规则,无法访问私人数据)。


Code like this:

int code = pthread_create(&d->thread_id, &attr, QThreadPrivate::start, this);

which QThreadPrivate::start is a static function.

So,what use is the fourth parameter this? And what is the difference if this is replaced by NULL?

解决方案

The fourth parameter of pthread_create is passed untouched to the thread function and allows that function to change behaviour based on that argument.

OpenGroup documentation for pthread_create, detailing this, can be found here.

In this case, it's simply passing the pointer to the current object, presumably so that the start function can use that to access member variables for the specific object.

If you pass NULL instead, the created thread will get NULL and won't be able to access object specific data (without crashing and burning badly with a null pointer dereference).

You may think that, because QThreadPrivate::start is a static function, it wouldn't be able to access non-static members any way (since it generally doesn't have an object to work on).

But that only applies to implicit access - there's nothing stopping you from accessing object data through an explicit this pointer, providing you follow the access rules (e.g., no access to private data).

这篇关于pthread_create函数中的第四个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆