Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

c++ - C ++线程可以暂停并存储其上下文以出租给另一个线程吗? (线程ID借用)(Can a C++ thread pause and store its context to rent to another? (thread ID borrowing))

Can a C++ thread A suspend its execution by storing that "pause" P in an object that can then be used in another thread B to run a function F in thread A?

(C ++线程A是否可以通过将“暂停” P存储在对象中来中止执行,然后将该对象在另一个线程B中用于在线程A中运行函数F?)

B could use P to unlock a mutex owned by A. Or F could lock a recursive mutex that was already locked by A, which is can be done safely (as safely as only recursive locking scheme when you have call backs) because:

(B可以使用P来解锁A拥有的互斥锁。或者F可以锁定已经由A锁定的递归互斥锁,这可以安全地完成(与只有回叫时的递归锁定方案一样安全),因为:)

  • the process is purely cooperative

    (这个过程是完全合作的)

  • real A isn't running while F run be B runs "in A", so only one execution has the lock

    (真正的A不在运行,而F运行则是B在“在A中运行”,因此只有一个执行具有锁定)

[Of course it's patently unsafe when done in a disorderly way, exactly like any recursive lock held while doing arbitrary call backs (that don't know the lock is already held and misinterpret being able to lock, thinking the mutex wasn't locked) or non recursive mutexes (might try to lock an already locked mutex and deadlock or cause an error), or essentially any scenario involving wait for a ressource in a call back called with a lock.]

([当然,以无序的方式进行操作显然是不安全的,就像在执行任意回调时所持有的任何递归锁一样(不知道该锁已被持有并且会误认为能够锁定,以为互斥锁未锁定)或非递归互斥锁(可能试图锁定已锁定的互斥锁和死锁或导致错误),或者实质上是涉及在调用带锁的回调中等待资源的任何情况。)

Because a thread cannot run in parallel with itself, A would could only restart once P is destroyed.

(由于线程无法与其自身并行运行,因此A仅在销毁P后才能重新启动。)

The point here is that the OS shouldn't get involved, only the C++ runtime : F would run immediately in OS thread B, not be scheduled for execution.

(这里的要点是, 操作系统不应该参与其中,只有C ++运行时 :F会立即在操作系统线程B中运行,而不是安排执行。)

The OS thread B would still be running, but executing as thread A.

(OS线程B仍将在运行,但将作为线程A执行。)

In other words, can C++ threads exchange identity in a cooperative way?

(换句话说, C ++线程可以以协作方式交换身份吗?)

  ask by curiousguy translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...