Reputation: 21381
I have an array of pthread_t
s which are started within a for-loop via pthread_create
.
I have a ton of variables that are declared beforehand and are important for the inner workings of the thread. I would like to have an anonymous inner function as start-routine of the pthread_create
like so:
pthread_create(threads[i], NULL,
{ inner function here }
, NULL);
I know that C++ doesn't have this in particular so I thought maybe lambdas could be of help or maybe someone has another idea so that I do not have to create a seperate method and hand over all those variables that come before pthread_create
.
Upvotes: 1
Views: 1177
Reputation: 33719
If a lambda expression does not capture anything, the lambda object can be converted to a C function pointer, so something like this will work:
pthread_t thr;
pthread_create (&thr, NULL,
[] (void *closure) -> void * {
return nullptr;
}, NULL);
The explicit return type of void *
is needed because the inferred one usually will not be correct. Since you cannot use captures, you need to use the closure
parameter to pass along a pointer to an object (and use static_cast
to cast it to the correct type in the lambda), and for life-time reasons, it is probably necessary to allocate that on the heap.
(Also note that pthreads[i]
as the first element to pthread_create
does not look right, it's a pointer used to return part of the result, the ID of the new thread.)
Upvotes: 5