c++multithreadingc++17conditional-variable

How immediately pause a thread?


Assum have two thread that one of them has more priority and they are running on same core (single core), I only want work just one thread at same time.(maybe you say that is not threading paradigm , but actually I just made my problem minimal here)

T1 ~~~e1~e2~e3~e4~...~~~~~~~eK~~~~~~~~...~~~ eN~~~~~ ///(e1...eN)packed as a task.
                |            |
T2 ~~~~~~~~~~~~pause~~~~~~continue~~~~~~~~~~~~~~~~~~ ///(pause & continue)is just title time for T1 that T2 is operating (T2 has more priority).

**~** is time , and **e** is expressions that is evaluate there. and whole of e1,e2,... is one function that is api caller function(task) , So I want just pause T1 there(~pause~) and run my T2 until it's finished ,and when finished continue T1.

Note: I could not changed **e** job (function).

What I know?

creating conditional_variable(CV) and when finished T2 notify CV to wake up , but it is not my achievement because I want make T1 exactly pause in the e4(pause time) immediately and continue T2 until it's finished(or my continue time).

my knowledge is same as: https://en.cppreference.com/w/cpp/thread/condition_variable#Example Do we have any thread::method that pause immediately(force context switch)?(I dont mean yield!)


Solution

  • C++ has no way of facilitating such a thing. You don't have that level of control over threads.

    On the OS level, that's what thread priorities are for. A higher-priority thread being ready should always be scheduled before a lower-priority thread. So you can use OS APIs to change the thread priorities for your threads, and should get approximately the right result - note, though, that this is approximate, because you have no guarantee the OS will immediately trigger a task switch on T2 getting ready.

    Overall, the whole thing sounds like an XY problem, and you would be better served by looking at the underlying problem and thinking of better ways of solving it.