1

I have an array of pthread_ts 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.

5
  • 5
    Why not use std::thread instead? The standard threads support lambdas, IIRC. Since you mention lambdas, you probably have std::thread too. Commented Jun 9, 2018 at 12:28
  • 1
    I suggest you do some more research about lambda expressions, a non-capturing lambda can be used as a function pointer. And read about std::thread as well. Commented Jun 9, 2018 at 12:28
  • Unfortunately I cannot use std::thread. Is it possible with pthreads? Commented Jun 9, 2018 at 12:30
  • 2
    Can you elaborate why std::thread would not be usable/possible while lambdas are? Commented Jun 9, 2018 at 12:33
  • 2
    If you have access to lambdas, you should have access to std::thread as well. They both came with the C++11 standard. Can you please elaborate on why you "cannot use std::thread"? Commented Jun 9, 2018 at 12:34

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.