开发者

Linux thread - simulate a restaurant table

开发者 https://www.devze.com 2023-03-04 23:14 出处:网络
i need to write a thread that simulates a table in a restaur开发者_Python百科ant. The table has four seats. At random times customers come and if they

i need to write a thread that simulates a table in a restaur开发者_Python百科ant. The table has four seats. At random times customers come and if they find an empty seat they stay, otherwise they leave. Can you please help me? Thanks


Here is some pseudocode:

-- A Table Thread

integer num_free_seats := 4

loop forever
   wait for customer c
   if num_free_seats > 0
        seat_customer(c)
        num_freeSeats := num_free_seats - 1
   else
        throw_out_customer(c)
   end if 


So you need a semaphore initialized to the number of seats at the table. The people (presumably other threads) check it. They wait on the semaphore until they get in. They post as they leave. If they really need to leave immediately if they don't get a seat then use something like sem_trywait. Use some kind of randomized sleep for how long they are at the table.

0

精彩评论

暂无评论...
验证码 换一张
取 消