1

Background

I'm taking an OS class this semester. I negotiated usage of C++ with professor, but I cannot use anything for which there is a linux system call (except memory management).

Problem

To implement interface

template<typename Callable, typename ... ArgTypes>
thread(Callable&& callable, ArgTypes&& ... args)

I need to pass an instantiation of a function template:

    template<typename Lambda>
    void *call_target(void *target)
    {
        Lambda *lambda = reinterpret_cast<Lambda *>(target);
        (*lambda)();
        //don't forget to cleanup
        delete lambda;
        return nullptr;
    }

pthread_create(&thread_handle,
               nullptr,
               &details::call_target<lambda_type>,
               target_function);

but pthread_create is declared with extern "C", so it will have C ABI. I've heard that one cannot pass C++ mangled function through C ABI. Am I correct?

Question

How to pass function template instantiation to extern "C" function in a portable way? Can I expect that on gcc 5.4 and Ubuntu 16.04 it will work reliably?


Full code on Wandbox.

Incomputable
  • 2,188
  • 1
  • 20
  • 40
  • 2
    A function pointer doesn't have a name, there isn't a problem – Passer By Mar 08 '18 at 09:00
  • Why not use `std::thread` ? – llllllllll Mar 08 '18 at 09:00
  • There are valuable lessons to learn when doing things in C. And if you have an assignment that involves modifying the kernel itself in your near future, you are going to need to do it in C anyway. Seems like the result of your negotiation is only added difficulty to a few assignments. – StoryTeller - Unslander Monica Mar 08 '18 at 09:08
  • @StoryTeller, it involves cleanups, and I wouldn't want to solve it without destructors. I actually wanted to know how `std::thread` is implemented, and to my surprise, it is easy to implement. The assignments don't involve any kernel modifications and mostly are in user-space. – Incomputable Mar 08 '18 at 09:09
  • @Incomputable - You are going to be forced into solving it without constructors if and when a kernel modifying assignments comes in. Difference is that your peers will have this assignment for practice, and you won't. – StoryTeller - Unslander Monica Mar 08 '18 at 09:11
  • Oh, no kernel modification? I see. – StoryTeller - Unslander Monica Mar 08 '18 at 09:11
  • @StoryTeller, I'm still merely second year student, I don't think modification of any real kernel is fit for me yet :) – Incomputable Mar 08 '18 at 09:12
  • For one, don't sell yourself short. And modifying the kernel is invaluable in learning how OS components work. You don't really understand process scheduling until you try to implement a new policy and cause a kernel panic :) – StoryTeller - Unslander Monica Mar 08 '18 at 09:15

0 Answers0