Good time of day. The parser receives 100 news and scatters all over three threads for writing. This I have already organized, each stream receives 100 news and writes them in JSON format in the same file, there are also locks when one of the threads writes. The task is to organize the last stream, which will block all three streams during some action from the user and watch what these streams have already written to the file.
1 answer
and writes them in json format into the same file
And why in this task to use streams? At the time of recording, two other streams are blocked? Per unit of time do you have only one stream per record?
The challenge is to organize ... a thread that will block all three threads
Let's say that this is another stream (and maybe use the main stream, otherwise it seems that after receiving the data it does nothing more and dies or hangs for good on .join), which checks the keystroke on the keyboard with rb (and it's easier just to stick time .sleep and wait 1 second) and stop the streams.
This can be done in several ways:
- Ask the operating system to freeze the thread ( https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-suspendthread ), but this design of the systems is considered bad tone
- Use the synchronization mechanism (lock difference)
There are different types of locks for all tastes and colors:
- Lock - Lock - who captured one and works, and the rest are waiting
- A multi-input lock - RLock - who captures can once again capture, but should release as many times (see recursion, etc.)
- Condition - Condition - everyone waits (wait) until the condition is met.
- Semaphore - Semafore - wait a few / work a few
- Event - Event - wait (wait) until someone releases (set)
- Barier - Barier - let go when all the horses come to the barrier (at the races)
Choose a convenient mechanism for you.
On the other hand, you already have one lock, and if someone takes it fourth, the other "writers" will be blocked.
- Yes, home OS task. To be honest, I understand that there are better 3 threads in the queue than 1, since may be more often performed than on hold. Most likely, the condition mechanism will do. Thank! - chattingtoofast
- Read my answer again. In your task, the threads are not needed in principle (that in three threads to write with a lock, that in one thread the total time will be the same, or even more, since the threads and locks must also be serviced). You have a bottleneck, not a CPU, but since the task is academic, that's fine. It's easier for you to grab the lock that blocks your write to the file, and not to fence another Condition. - Witold