0

我曾经在访问共享数据时使用临界区(在c ++中)来阻止theads的执行,但是为了工作,它们必须等到数据没有被使用后再阻塞,也许最好在主线程或线程中使用它们。然后,如果我希望我的主程序具有优先级并且不被阻塞,我必须使用其中的关键部分来阻塞其他线程还是相反?

4

2 回答 2

9

您似乎对关键部分是什么以及它们如何工作有相当的误解。

一般而言,临界区 (CS) 是需要“独占”运行的一段代码——即,您需要确保在任何给定时间只有一个线程正在执行该段代码。

由于该术语在大多数环境中使用,CS 实际上是一个互斥体——互斥信号量(又名二进制信号量)。它是一种数据结构(和一组函数),用于确保一段代码被独占执行(而不是引用代码本身)。

在任何情况下,CS 仅在/如果您有一些将在多个线程中执行的代码时才有意义,并且您需要确保它在任何给定时间仅在一个线程中执行。这通常是当您拥有一些共享数据时,如果多个线程一次尝试操作它,这些数据可能并且将会被破坏。当/如果出现这种情况,您需要为每个操作该数据的线程“使用”关键部分,以确保共享数据没有损坏。

确保特定线程保持响应是一个完全独立的问题。在大多数情况下,这意味着使用队列(一种可能性)以允许线程快速将任务“移交”给其他线程,而竞争最小(即,在处理数据的过程中不使用 CS, CS 仅持续足够长的时间以将数据结构放入队列中,而其他一些线程则从那里进行处理)。

于 2011-02-17T15:13:23.710 回答
0

You cannot say "I am using critical section in thread A but not in thread B". Critical section is a piece of code that accesses shared resource. When this code is executed from two threads that run in parallel, shared resource might get corrupted so therefore you need to synchronise access to it: you need to use some of synchronisation objects (mutexes, semaphores, events...depending on the platform and API you are using). ThreadA locks the critical section so ThreadB needs to wait till ThreadA releases it.

If you want your main thread to block (wait) less than working thread, set working thread priority to be lower than priority of the main thread.

于 2011-02-17T15:26:03.027 回答