0

假设我有一个互斥锁、两个线程、一个函数和一个循环(伪代码)。功能:

void Update(){
    Mutex.enter();
    ...// time: 10 ms
    Mutex.leave();
}

主要.cpp:

void main(){
    ...// Starting thread
    while(true)
        Update();
}

线:

void Thread(void *){
    Mutex.enter();
    ... // 
    Mutex.leave();
}

但是Function调用不断,所以Mutex小时候是空闲的。线程进入 Mutex 的机会有多大?如果低,如何解决?

4

2 回答 2

2

如果您使用的是 boost 线程(链接),那么我会使用yield(). 它将允许任何其他“等待”线程“有机会”运行。

也可能有一种 win32 或 pthreads 方式来执行此操作。

编辑:顺便说一句,在锁yield() 使用。如果它在锁内,显然那将毫无用处。

Edit2:这里是不同平台的功能:

  • Win32:SwitchToThread() msdn 链接
  • Linux/Unix pthreads: `pthread_yield()' link

If you're not on any of those platforms, read the descriptions at those links, and look for a function that does the same thing in your framework.

于 2012-05-01T15:15:45.860 回答
0

From the pseudo-code you showed it seems like there's no cooperation between threads. If thread2 is lucky to grab the mutex before the call to the first Update() is placed then for the whole lifetime of thread2 Update() functions will not be called. It looks like a flawed design to me. If thread2 is doing the work and 'main' thread is calling Update() function to monitor and report the progress of whatever is happening in thread2 thread routine, then it would make much more sense to have thread1 (the main one) wait on a update_required signal and thread2 (the one that is progressing with work) would do the work, then fill-in a struct variable with all the data needed to report the progress and signal thread1 to use the data and report the progress. Using a ring buffer of such struct variable could eliminate the need for mutexes altogether.

于 2012-05-02T13:34:50.287 回答