Alexey
да
Alexey
и мне нужно видеть список всех возможных типов сообщений, компактно
Alexey
то есть тут бы какой-нибудь алгебраический тип данных подошел бы, но в плюсах их нема
Alexey
и жаль что switch нельзя сделать по варианту
Alexey
нету паттерн матчинга адекватного 😕
Alexey
а visit стукнет по рукам если я не все варианты варианта обработал? 🙂
Anatoly
для неспециализированных типов
Anatoly
failsafe
Alexey
ok. хотелось конечно проверки на этапе компиляции.. но ок
Alexey
всегда можно тестами покрыть
Anatoly
Alexey
а если не все перечислю, ошибка компиляции будет?
Anatoly
тогда получишь по рукам
Alexey
гут. спасибо
Roman
volatile int a = 3;
std::cout « (a+a) « std::endl;
Не могу понять, почему это UB? Какое рациональное обьяснение?
🙃
Roman
Ignat
А почему Вы спрашиваете?
Roman
Знакомый задал вопрос, почему здесь неопределенное поведение, ничего в стандарте по этому поводу найти не могу
Roman
Академический интерес
🙃
может только если a меняют в другом месте
Roman
volatile int a = 3;
std::cout « a « std::endl;
уже не UB, как мне сказали
Roman
Что-то вроде подсказки, но все равно непонятно
Vladislav
видимо речь о том, что порядок чтений в (a + a) не определен, но это не UB в смысле стандарта
🙃
спроси этого академика меняют ли a в другом треде
🙃
в другом треде например
🙃
ну так и всё
Roman
Не треде, откуда-то извне
🙃
пока его меняют не ясно какое число прочитается
🙃
изменение то может быть побайтовым
🙃
изменение int'а не атомарно
Vladislav
https://www.beningo.com/understanding-volatile-access-warnings/
🙃
т.е если ты там нулю присваиваешь FFFFFFFF то можно вполне словить момент когда будет 0000FFFF
🙃
🙃
на x86 байт и меньше атомарны вроде
Ignat
гонки по данным — UB, volatile тут ни при чём
🙃
ну да, может задающий вопрос и не это имеет ввиду
Ioann_
Волатиль это ж анти кеш?
Ioann_
Анти кеш из регистра я думал. Хм
🙃
Даже гонки нет?
Anatoly
Проверяй информацию
Anatoly
volatile object - an object whose type is volatile-qualified, or a subobject of a volatile object, or a mutable subobject of a const-volatile object. Every access (read or write operation, member function call, etc.) made through a glvalue expression of volatile-qualified type is treated as a visible side-effect for the purposes of optimization (that is, within a single thread of execution, volatile accesses cannot be optimized out or reordered with another visible side effect that is sequenced-before or sequenced-after the volatile access. This makes volatile objects suitable for communication with a signal handler, but not with another thread of execution, see std::memory_order). Any attempt to refer to a volatile object through a non-volatile glvalue(e.g. through a reference or pointer to non-volatile type) results in undefined behavior.
Roman
Нашел все таки
Roman
Неопределенное поведение
Roman
Except where noted, evaluations of operands of individual operators and of subexpressions of individual expressions are unsequenced. [ Note: In an expression that is evaluated more than once during the execution of a program, unsequenced and indeterminately sequenced evaluations of its subexpressions need not be performed consistently in different evaluations. — end note ] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.
[ Example:
void f(int, int);
void g(int i, int* v) {
i = v[i++]; // the behavior is undefined
i = 7, i++, i++; // i becomes 9
i = i++ + 1; // the behavior is undefined
i = i + 1; // the value of i is incremented
f(i = -1, i = -1); // the behavior is undefined
}
— end example ]
When calling a function (whether or not the function is inline), every value computation and side effect associated with any argument expression, or with the postfix expression designating the called function, is sequenced before execution of every expression or statement in the body of the called function. [ Note: Value computations and side effects associated with different argument expressions are unsequenced. — end note ] Every evaluation in the calling function (including other function calls) that is not otherwise specifically sequenced before or after the execution of the body of the called function is indeterminately sequenced with respect to the execution of the called function.9 Several contexts in C++ cause evaluation of a function call, even though no corresponding function call syntax appears in the translation unit. [ Example: Evaluation of a new expression invokes one or more allocation and constructor functions; see [expr.new]. For another example, invocation of a conversion function ([class.conv.fct]) can arise in contexts in which no function call syntax appears. — end example ] The sequencing constraints on the execution of the called function (as described above) are features of the function calls as evaluated, whatever the syntax of the expression that calls the function might be.
Roman
Но как-то это все равно непонятно
Roman
Roman
Вопрос то непростой оказался...
Anatoly
Ильюха, ну хоть в стандарт загляни
Anatoly
А a+a? Где здесь glvalue?
Ioann_
Vladislav
Alexey
что-то я совсем запутался, где в a+a non-volatile glvalue?
Constantine
Михаил
Доброго времени суток! Возник такой вопрос: есть 2 консольных приложения, оба запускаются через пайплайн (т.е. вывод (stdout) одного является входом (stdin) для другого процесса). Приложение которое генерит данные многопоточное, в каждом потоке производятся вычисления и готовится символьный буфер, далее происходит блокировка (spin_lock, чтобы избежать перехода в режим ядра) и весь буфер сбрасывается в stdout (чтобы уменьшить число системных вызовов). Профайлер показывает что больше всего времени уходит на запись буфера в stdout. Можно ли как-то ускорить вывод в stdout? Я пробовал: писать через cout.write(...) с sync_with_stdio(false), писать через fwrite/write, играться размером буфера, отключать буферизацию, все результаты отличаются максимум на 20-30% (если это как-то может помочь - то при перенаправлении в файл пропускная способность 200-230 Мб/с (походу край для моего hdd)). Может кто встречался/знает какие библиотеки/советы на эту тему?
Катлет
ос?
Constantine
Я полагаю товарищ хочет вывод быстрый
Constantine
Я полагаю консольки достаточно медленные, как и пайпы
Михаил
Ускорить именно передачу, т.к. с генерацией все норм
Konstantin
https://www.reddit.com/r/unix/comments/6gxduc/how_is_gnu_yes_so_fast/?st=j3v3iw3c&sh=5651ea3c
Anton
"spin_lock, чтобы избежать перехода в режим ядра" ... )
Катлет
Катлет
не очень понятна цель, какая нужна скорость?
Михаил
Читает stdin и тоже производит счет, видно что оно простаивает пока ждет данные
Mikhail
Михаил
Т.е. первое не успевает запитать данными второе
Anton
там наверно одно из ядер кипятится на этом спинлоке пока консоль ворочается
Михаил
Это я понимаю)
Катлет
линукс?
сколько ядер?
Михаил
От второго приложения нет исходников к сожалению из -за этого и пайпы
Катлет
может, там какая-то извесная программа
Катлет
без понятия, кто там ест стдин