C++ 使用C库函数setcontext()、getcontext()等实现Fork
我正在使用C函数getcontext()、setcontext()和makecontext()编写一个自定义用户级线程库。我在实现thread_fork()函数的逻辑时遇到困难。基本上,thread_fork()函数创建新线程,当从thread_fork()返回时,新创建的线程应接收0的返回值,而原始线程应接收threadid作为返回值C++ 使用C库函数setcontext()、getcontext()等实现Fork,c++,multithreading,unix,pthreads,C++,Multithreading,Unix,Pthreads,我正在使用C函数getcontext()、setcontext()和makecontext()编写一个自定义用户级线程库。我在实现thread_fork()函数的逻辑时遇到困难。基本上,thread_fork()函数创建新线程,当从thread_fork()返回时,新创建的线程应接收0的返回值,而原始线程应接收threadid作为返回值 void Thread1Example(int) { std::cout << "B" << std::endl; thread
void Thread1Example(int) {
std::cout << "B" << std::endl;
thread_exit();
}
void main() {
Init(); // Initialize thread library data structures
std::cout << "A" << std::endl;
int thread1 = thread_fork(); // Fork a new thread and returns 0 & threadID
if (thread1==0)
Thread1Example();
std::cout << "C" << std::endl;
}
我想知道一些细节,一个thread\u fork()函数如何使用C上下文库(setcontext()、getContext等)返回两个不同的值。您是否实现了
thread\u fork
?实现在哪里?我需要使用C库函数getcontext()、setcontext()、swapcontext()等实现thread_fork()函数。但是我无法找到返回上述两个不同值的方法。为什么您认为可以使用这些函数呢?切换执行上下文很好,但您打算如何安排它?@Wajih我无法以任何方式实现fork
等价物。fork
函数非常复杂,它得益于内核的支持。您更应该尝试实现类似于pthread\u create
的等效程序,并为线程调度实施某种协作策略。也许这会有帮助:
Console Output:
ABC