这种情况下如何设计线程同步
我的需求如下
- 有一个多线程的进程。
- 其中一个线程 (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)
这很好用。但我想知道是否有更简单的方法可以做到这一点。
My requirement is as follows
- There is a process with multiple threads.
- One of the threads (T1), gets triggered by a user event
- There is a task that needs to be done in a separate thread(T2), which should be spawned by T1
- Now, T1 should check that the system is not already doing the task in T2. If its not, then it should spawn T2 and then exit. If T2 is still running, then I should just return from T1 by logging an error. I do not want to hold T1 until T2 is complete.
- T2 will usually take a long time. So in case T1 is triggered before T2 has finished it should just return with an error.
- The intention is under no circumstance we should have two threads of T2
I am using a mutex and semaphore to do this, but there may be a simpler way.
Here is what i do.
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)
And this works fine. But I want to know if there is a simpler way of doing this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不要使用这样的互斥体。互斥锁的持有时间应尽可能短。在这种情况下,有一个布尔标志
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
Do not use a mutex like this. Mutex locks should be held for the minimum time necessary. In this case, have a boolean flag
t2_running
, which is protected by the mutex. In T1 do:g_mutex
t2_running
t2_running
was set, unlockg_mutex
and exit with errort2_running
g_mutex
g_semaphore
T2 can then do:
g_semaphore
g_mutex
t2_running
g_mutex