我的要求如下
我使用互斥锁和信号量来执行此操作,但可能有一种更简单的方法。 这就是我的所作所为。
Mutex g_mutex;
Semaphore g_semaphone;
T1:
if TryLock(g_mutex) succeeds // this means T2 is not active.
spawn T2
else // This means T2 is currently doing something
return with an error.
wait (g_sempahore) // I come here only if I have spawned the thread. now i wait for T2 to pick the task
// I am here means T2 has picked the task, and I can exit.
T2:
Lock(g_mutex)
signal(g_semaphore)
Do the long task
Unlock(g_mutex)
这很好用。但我想知道是否有更简单的方法。
答案 0 :(得分:0)
请勿使用此类互斥锁。互斥锁应保持所需的最短时间。在这种情况下,有一个布尔标志t2_running
,它受互斥锁保护。在T1中:
g_mutex
t2_running
t2_running
,请解锁g_mutex
并退出并显示错误t2_running
g_mutex
g_semaphore
T2可以这样做:
g_semaphore
g_mutex
t2_running
g_mutex