首页 文章

忙着等待使用信号量

提问于
浏览
-1

我正在使用信号量做一些同步线程 . 现在我要做的是等待一些客户线程使用floor_clerk线程中的信号量到达队列 . 我之前使用while循环做它 . 客户线程也必须等待,直到map_clerk也使用信号量帮助它 . 我之前使用深度睡眠做这件事 . Any wait must be implemented using P(semaphores) (acquire) 这是等待的方式 . 这是任务: Floor clerks wait (use semaphores) for customers to arrive; then, they help them with whatever information they need. However, floor clerks can only help one customer at a time; therefore, a customer must wait (use semaphores) for an available clerk to help him/her.

我以前的Floor_clerk等待代码是:

while (done != Main.csize) {        
    //wait while their is no customer in queue
    while (queue.isEmpty() && done != Main.csize) {
    }

    //while their is a customer in queue assist customers
    while (queue.size() != 0 && done != Main.csize) {
        //some stuff to do
    }
}

请帮我在这里实现信号量 .

1 回答

  • 0

    只需将您的客户端存储在阻塞队列中,然后使用 take() 方法阻止,直到有可用的客户端进行服务 . 那里已经内置了's no need to separate the queue and the blocking mechanism since it' .

    如果你必须使用信号量,信号量工作的基本上是一个阻塞队列"permits."你应该考虑这个阻塞功能如何适合你想要做的事情 . 当有客户端可用时,您需要 release() 许可并允许服务 acquire() . 如果没有任何许可,那么该服务将在 acquire() 上阻止 .

    // Add client
    queue.add(client);
    semaphore.release();
    
    // Clerk loop
    while (true) { // Whatever condition
        semaphore.acquire(); 
        Client client = queue.remove();
        // ...
    }
    

相关问题