有关Getcontext函数的问题 [英] Question on Getcontext function

查看:39
本文介绍了有关Getcontext函数的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现用户级线程库. Getcontext函数用于将当前线程的上下文保存在内存中. Getcontext函数在2种情况下使用

I am trying to implement a user level thread library . Getcontext function is used to save the context of the current thread in memory . The function Getcontext are used in 2 cases

  1. 要保存当前上下文并移至下一个线程
  2. 创建新上下文

但是,在两种情况下,它都返回相同的值.那么,如何区分这两种情况?

But, in both cases, it returns the same value. So, how do i differentiate between these 2 cases ?

谢谢

推荐答案

getcontext不会移到新线程,setcontext()和swapcontext()会移到新线程. 您的线程库应至少实现以下两个功能:

getcontext does not move to a new thread, setcontext() and swapcontext() does. Your thread library should implement at least these 2 features:

  1. 能够创建新线程.

  1. Ability to create a new thread.

能够切换到另一个线程.

Ability to switch to another thread.

在第一种情况下,您调用getcontext()初始化ucontext_t,为堆栈分配内存并在ucontext_t中设置堆栈指针,然后调用makecontext()来使用启动函数初始化上下文.

In the first case, you call getcontext() to initialize a ucontext_t , allocate memory for a stack and set the stack pointer in the ucontext_t, then you call makecontext() to initialize the context with a starting function.

在第二种情况下,您调用getcontext()来存储当前线程的上下文,并调用setcontext()来切换到先前存储的另一个线程.或者,更常见的是,您将使用swapcontext结合get/setcontext调用. 参见例如此处,这是使用get/setcontext实现协作线程的一种非常简单的方法.

In the second case, you call getcontext() to store the context for the current thread, and setcontext() to switch to another thread you have previously stored. Or, more commonly, you'd use swapcontext combine the get/setcontext calls. See e.g. here for a very simple way of implementing cooperative threads with get/setcontext.

这篇关于有关Getcontext函数的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆