我的要求如下
- 有一个具有多个线程的进程。
- 其中一个线程 (T1) 由用户事件触发
- 有一个任务需要在一个单独的线程(T2)中完成,它应该由 T1 产生
- 现在,T1 应该检查系统是否已经在 T2 中执行任务。如果不是,那么它应该生成 T2 然后退出。如果 T2 仍在运行,那么我应该通过记录错误从 T1 返回。我不想在 T2 完成之前持有 T1。
- T2 通常需要很长时间。因此,如果 T1 在 T2 完成之前被触发,它应该只是返回一个错误。
- 意图是在任何情况下我们都应该有两个 T2 线程
我正在使用互斥锁和信号量来执行此操作,但可能有更简单的方法。这就是我所做的。
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)
这很好用。但我想知道是否有更简单的方法可以做到这一点。