简体   繁体   English

pthread_create:按值传递参数

[英]pthread_create: Passing argument by value

I wonder why cannot we pass objects by value to the functions on which we create threads. 我想知道为什么我们不能按值将对象传递给创建线程的函数。

Is there a logical reason behind it? 背后有逻辑原因吗? Would it be harmful if the language allowed passing by value? 如果语言允许按值传递,是否有害?

pthread is a C style interface. pthread是C风格的接口。 To allow more flexibility than "pass an integer", it has to be a pointer. 为了提供比“传递整数”更大的灵活性,它必须是一个指针。 A void * is the most flexible way to pass arbitrary things in C. In C, you can of course pass a struct by value, but which struct needs to be known by both the source and the destination function at compile time (and the same every time, so we can't use struct X in one of our threads, and struct Y in another thread). void *是在C中传递任意事物的最灵活的方法。在C中,您当然可以按值传递一个struct ,但是在编译时,源函数和目标函数都必须知道该结构(并且相同每次,因此我们不能在一个线程中使用struct X ,而在另一个线程中使用struct Y )。

In C++ we can of course use classes and templates to allow almost anything to be passed to almost any type of function. 在C ++中,我们当然可以使用类和模板来将几乎所有内容传递给几乎任何类型的函数。

The C++ 11 std::thread allows you to use various C++ style things to overcome the "C-ness" of pthreads (and subject to an available implementation for the target system, use threads without pthreads). C ++ 11 std::thread允许您使用各种C ++样式的东西来克服pthread的“ C-ness”(并且视目标系统的可用实现而定,使用不带pthread的线程)。

[This is not unique to pthreads . [这不是pthreads独有的。 Both OS/2 and Windows thread implementations take a void * as the argument to the thread function] OS / 2和Windows线程实现都将void *作为线程函数的参数]

POSIX threads is a C API. POSIX线程是C API。 C does not provide language facilities like copy constructors and so it is not possible to copy any object by value without additional information (ie passing in function that are aware of the type and can do the job of allocating memory and copying the data). C没有提供像复制构造函数这样的语言功能,因此,如果没有附加信息(即传递知道类型并可以完成分配内存和复制数据的功能)的信息,就不可能按值复制任何对象。 However, that API would be over-complicated for no good reason. 但是,没有充分的理由,该API会过于复杂。

That being said, you can pass any object by value as long as its size is not greater than sizeof(void *) . 就是说,您可以按值传递任何对象,只要其大小不大于sizeof(void *)

Since you have tagged your question as C++, C++ does allow to pass a function with as many arguments as you want through variadic templates. 由于您已将问题标记为C ++,因此C ++确实允许通过可变参数模板传递带有所需参数的函数。 See std::thread for more details. 有关更多详细信息,请参见std::thread

The argument to pthread_create is typed as a pointer, to be as flexible as possible, but that doesn't mean you can't pass an int . pthread_create的参数键入为指针,以使其尽可能灵活,但这并不意味着您不能传递int Just cast it back to an int in the start_routine . 只需将其转换回start_routineint As long as the passed-by value argument is smaller than a pointer you should be OK. 只要传递的值参数小于指针,您就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM