我的要求如下
我正在使用互斥量和信号量来执行此操作,但是可能有一种更简单的方法。
这是我的工作。
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)
而且这很好。但是我想知道是否有更简单的方法可以做到这一点。
最佳答案
不要使用这样的互斥锁。互斥锁应保持最短的时间。在这种情况下,有一个 bool 标志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
关于multithreading - 在这种情况下如何设计线程同步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8925251/