170 похожих чатов

I am really glad someone asked this question, because for

the longest time I also believed threads were necessary to concurrency. When I first saw event loops, I thought they were a lie. I thought to myself "there's no way this code can be concurrent if it runs in a single thread". Keep in mind this is after I already had gone through the struggle of understanding the difference between concurrency and parallelism.

After research of my own, I finally found the missing piece: select(). Specifically, IO multiplexing, implemented by various kernels under different names: select(), poll(), epoll(), kqueue(). These are system calls that, while the implementation details differ, allow you to pass in a set of file descriptors to watch. Then you can make another call that blocks until the one of the watched file descriptors changes.

Thus, one can wait on a set of IO events (the main event loop), handle the first event that completes, and then yield control back to the event loop. Rinse and repeat.

How does this work? Well, the short answer is that it's kernel and hardware-level magic. There are many components in a computer besides the CPU, and these components can work in parallel. The kernel can control these devices and communicate directly with them to receive certain signals.

These IO multiplexing system calls are the fundamental building block of single-threaded event loops like node.js or Tornado. When you await a function, you are watching for a certain event (that function's completion), and then yielding control back to the main event loop. When the event you are watching completes, the function (eventually) picks up from where it left off. Functions that allow you to suspend and resume computation like this are called coroutines.

1 ответов

7 просмотров

и что это?

Похожие вопросы

Обсуждают сегодня

Всем привет, написал код ниже, но он выдает сегфолт, в чем причина? #include <stdio.h> #include <stdlib.h> #include <string.h> struct product { char *name; float price; };...
buzz базз
75
Хотел бы спросить у знающих, правильную ли я выбрал книгу для начала изучения ассемблера Юрова В.И ? Или есть более лучшие книги для начала обучения?
Botsman
31
$params = [ 'formid' => 'feedbackForm', 'formTpl' => '@CODE: <form class="form-validate" data-id="ajax_form"> <fieldset class="margin-bottom-md"> ...
Pathologic
1
Всем привет, подскажите/посоветуйте пожалуйста. Фаердак компоненты, имею одно место где бизнес хочет видеть при открытии формы список всех клиентов, это порядка 30к. Мои дово...
Sasha Sch
7
Здравствуйте. Задача состоит в том, чтобы сделать real-time чат в мобильном приложении. После передачи сообщения пользователем через веб-сокеты, для основного и долговременног...
🐾
5
А как лучше конвертировать физический адрес в виртуальный при маппинге? В случае ядра у меня, например, direct mapping, первые 768МБ я как есть мапплю в higher half, а остальн...
Evg Resh
8
Книга Юрова В.И пойдёт для обучения?
Botsman
24
Всем доброго дня, ребят подскажите пожалуйста, если в курсе по ассемблеру используется MASM32, могу ли я использовать FASM? В чем явная разница и будет ли у меня все работать?
Botsman
17
Где можно найти примеры эффективного "асинхронного" tcp сервера на C? Я видел select, kqueue, poll, epoll и т.д. Ввод-вывод неблокирующий, но обработка клиентов блокирующая
#
10
Hi Everyone! To all Are you Looking for Interview Support at the Lowest Price? Look no further! Then contact us 👉We offer Interview Support :-for a low cost variety of tech...
Rambabu Nallamilli
3
Карта сайта