简体   繁体   中英

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. 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).

In C++ we can of course use classes and templates to allow almost anything to be passed to almost any type of function.

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).

[This is not unique to pthreads . Both OS/2 and Windows thread implementations take a void * as the argument to the thread function]

POSIX threads is a 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). However, that API would be over-complicated for no good reason.

That being said, you can pass any object by value as long as its size is not greater than 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. See std::thread for more details.

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 . Just cast it back to an int in the start_routine . As long as the passed-by value argument is smaller than a pointer you should be OK.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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