ModernesCpp | Blog library
kandi X-RAY | ModernesCpp Summary
kandi X-RAY | ModernesCpp Summary
Project for translating the posts of my blog successively to English. You can see the English posts on www.ModernesCpp.com. The source code is in my repo ModernesCppSource (
Support
Quality
Security
License
Reuse
Top functions reviewed by kandi - BETA
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample of ModernesCpp
ModernesCpp Key Features
ModernesCpp Examples and Code Snippets
Community Discussions
Trending Discussions on ModernesCpp
QUESTION
// spinlockAcquireRelease.cpp
#include
#include
class Spinlock{
std::atomic_flag flag;
public:
Spinlock(): flag(ATOMIC_FLAG_INIT) {}
void lock(){
while(flag.test_and_set(std::memory_order_acquire) ); // line 12
}
void unlock(){
flag.clear(std::memory_order_release);
}
};
Spinlock spin;
void workOnResource(){
spin.lock();
// shared resource
spin.unlock();
}
int main(){
std::thread t(workOnResource);
std::thread t2(workOnResource);
t.join();
t2.join();
}
...ANSWER
Answered 2022-Jan-12 at 22:30std::memory_order_acq_rel
is not required.
Mutex synchronization is between 2 threads.. one releasing the data and another acquiring it.
As such, it is irrelevant for other threads to perform a release or acquire operation.
Perhaps it is more intuitive (and efficient) if the acquire is handled by a standalone fence:
QUESTION
I understand atomic_thread_fence
in C++ is quite different with atomic store/loads, and it is not a good practice to understand them by trying to interpret them into CPU(maybe x86)'s mfence/lfence/sfence.
If I use c.load(memory_order_acquire)
, no stores/loads after c.load
can be reordered before c.load
. However, I think there are no restriction to stores/loads before c.load
. I mean some stores/loads before c.load
can be reordered after it theoretically.
However when it comes to atomic_thread_fence(memory_order_acquire)
, it involves 3 kinds of objects: the fence, store/loads before this fence and store/loads after this fence.
I think the fence will certainly prevent store/loads after this fence being reordered before itself, just like atomic store/load. But will it prevent store/loads before this fence being reordered after itself?
I think the answer is yes with the following searching:
-
An acquire fence prevents the memory reordering of any read which precedes it in program order with any read or write which follows it in program order.
So he does not specify a direction.
In modernescpp
there is an additional guarantee with the acquire memory barrier. No read operation can be moved after the acquire memory barrier.
So I think he say yes directly?
However, I find no "official" answer in cppreference, it only specifies how fences and atomics interact with each other in different threads.
but I am not sure, so I have this question.
...ANSWER
Answered 2022-Jan-07 at 11:12After reading your question more carefully, looks like your modernescpp link is making the same mistake that Preshing debunked in https://preshing.com/20131125/acquire-and-release-fences-dont-work-the-way-youd-expect/ - fences are 2-way barriers, otherwise they'd be useless.
A relaxed load followed by an acquire fence is at least as strong as an acquire load. Anything in this thread after the acquire fence happens after the load, thus it can synchronize-with a release store (or a release fence + relaxed store) in another thread.
But will it prevent store/loads before this fence being reordered after itself?
Stores no, it's only an acquire fence.
Loads, yes. In terms of a memory model where there is coherent shared cache/memory, and we're limiting local reordering of access to that, an acquire fence blocks LoadLoad and LoadStore reordering. https://preshing.com/20130922/acquire-and-release-fences/
(This is not the way ISO C++'s formalism defines things. It works in terms of happens-before rules that order things relative to a load that saw a value from a store. In those terms, a relaxed load followed by an acquire fence can create a happens-before relationship with a release-sequence, so later code in this thread sees everything that happened before the store in the other thread.)
QUESTION
Is it the max allowed value of the inner counter
? But how is it possible to talk about minimum max value? Shouldn't max
value be const? How can it be changed? What is difference between LeastMaxValue
and counter
?
As its name indicates, the LeastMaxValue is the minimum max value, not the actual max value. Thus max() can yield a number larger than LeastMaxValue. https://en.cppreference.com/w/cpp/thread/counting_semaphore/max
...The constructor call
std::counting_semaphore<10> sem(5)
creates a semaphore sem with an at least maximal value of 10 and a counter of 5. https://www.modernescpp.com/index.php/semaphores-in-c-20
ANSWER
Answered 2021-Dec-26 at 21:19Shouldn't max value be const?
Yes. In fact, counting_semaphore::max()
is required to be constexpr
, meaning that it is not just constant, but a compile-time constant. For a given LeastMaxValue
, the max
can vary from compilation to compilation, but no more than that.
Perhaps that's the source of your confusion? From the perspective of watching a program run, the max()
corresponding to a given LeastMaxValue
is constant. From the perspective of making sure code works across multiple compilers and platforms, max()
can vary.
When you declare a variable whose type is std::counting_semaphore<5>
, you are declaring that the variable's counter will need to go up to 5
. This becomes a request to the compiler that the counter be able to hold 5
. If it happens that the counter can hold 255
, well that's fine. You don't plan to raise the counter that high, so your code will function correctly with that maximum.
Look at the constructor of std::counting_semaphore
. This will function correctly as long as the initial value of the counter satisfies 0 <= initial
and initial <= max()
. The first condition is easy to satisfy, but how do you satisfy the second? You can do this by satisfying a more stringent requirement – make sure initial <= LeastMaxValue
. This is more stringent, because the compiler is obligated to ensure that for your choice of LeastMaxValue
, the corresponding max()
is at least as large; that is, LeastMaxValue <= max()
. As long as you specify a high enough value for LeastMaxValue
, the constructor will work as intended with your initial value.
There is a similar requirement for release()
to function correctly. Correct behavior requires that the counter not exceed max()
, which you can ensure by not exceeding LeastMaxValue
. You do get correct behavior if the counter ends up between LeastMaxValue
and max()
, but then you are subject to the whims of your compiler. A different compiler might give you a lower max()
. If you want to play in this area, your code needs to adapt to a max()
that can change from compiler version to compiler version.
You could think of this as being similar to int_fast8_t
in that the 8
specifies the minimum size of the type, but the compiler can give you more. You are guaranteed that the maximum value that can be stored in this type is at least 127
(the minimum max value). You might get more than 8 bits in this type, and hence be able to store higher values, but you might not.
QUESTION
So I am trying to use counting_semaphore in visual studio 2019 and 2022 but all I get is " std has no member counting_semaphore".
I tried it in visual studio 2019 after adding the clang 11 in individual components but I still get the same error. Then I was like ok it doesn't support C++20. So I thought maybe that's why it doesn't work.
Then I saw Vs2022 Preview supports C++20. So I installed it, included and still I cant do "std::counting_semaphore<5> slots(5);" as it says std doesn't have a member called counting semaphore.
I also installed clang12 in the individual components in 2022 preview installer and still I didn't get it to work.
I am not sure what I am doing wrong.
I see examples online:
https://www.modernescpp.com/index.php/semaphores-in-c-20 https://en.cppreference.com/w/cpp/thread/counting_semaphore
telling how to use it, but when I put the code in vs it just doesn't work.
I can do "view code" on #include and it shows implementation of counting_semaphore and yet I cant use it!!!
Kindly someone please clarify what I am doing wrong!!!
...ANSWER
Answered 2021-Aug-04 at 05:40Whether you have set the c++ language standard?
Property -> General -> C++ Language Standard -> /std: c++ latest
I could build successfully in visual studio 2022 preview 17.0.0 preview 2.0.
And I could also build successfully in visual studio 2019.
QUESTION
I am experimenting with modules in clang, and would like to include the standard lib as modules instead of as includes.
Currently I do this
...ANSWER
Answered 2021-Feb-28 at 18:02The C++20 standard does not include module definitions for the C++ standard library. Visual Studio does (unfortunately), and a lot of bad sites out there will act like this is standard. But it's not; it's just a Microsoft thing.
If you want to include the C++ standard library through a module across platforms, you will have to either use import
syntax or write your own standard library modules that import the headers and export specific C++ declarations.
QUESTION
I am trying to write a custom formatter to help me print vectors. I am attempting to maintain the format specifiers so that each item in the vector is formatted the same way.
I have taken most of my inspiration from this tutorial, and the docs
...ANSWER
Answered 2021-Mar-22 at 19:31You can get rid of your parse
implementation and use the inherited function, and use fmt::formatter::format(item, context)
inside your format
to output each item (godbolt demo):
QUESTION
In the docs on std::span constructors, there isn't one that accepts an std::vector.
Then, how come this code (source page) compiles?
...ANSWER
Answered 2020-Nov-18 at 20:11It's the constructor (7) in the overload set:
QUESTION
When seaching for std::future::then on google, the top result is a stackoverflow question about the status of the function in c++17. Now that c++20 has been finalized and Clang and GCC is well into implementing c++20, I am left wondering what is the status of the function and the Concurrency TS generally?
It isn't mentioned on the implementation status page of libc++, libstdc++ or the implementation status page maintained by cppreference), and the TS page on cppreference doesn't say anything about current status.
I have also tried running some very simple examples on Godbolt, but neither are able to find , and not because it has been moved to the header (neither can find future::then.
Additionally, the internet has not been especially helpful. At least I can only find blog posts from 1-2 years ago talking about "hoping" to get the Concurrency TS in c++20, but cannot find any mentions in numerous overviews of new c++ 20 features (a few examples.
Has the Concurrency TS been dropped?
...ANSWER
Answered 2020-Aug-11 at 14:32Has the Concurrency TS been dropped?
Yes.
P1445 discusses this, SG1 voted to withdraw the TS. Note that atomic smart pointers, latches, and barriers are in C++20.
As far as improving future
goes, the direction there is called executors and the design currently being iterated on is P0443, which allows for lazy composition of work in a way that would be much more efficient than future::then
. Two of the authors gave a talk on this at CppCon that goes into the issues pretty well.
QUESTION
I am currently working on a problem that requires a few concepts to be tied together. I first define a class "Base" which uses the CRTP (see https://www.modernescpp.com/index.php/c-is-still-lazy) to achieve run-time polymorphism. I then define two derived classes of Base called "Derived1" and "Derived2" as examples of how this polymorphism will be used. This all works as expected until another concept of "Agent" is introduced. Agent will have various state variables as well as a pointer to its corresponding derived class. The goal is to have many such agents with potentially different derived classes. I'd like to store all of these objects in the same array. However, this seems to be ill-defined, as each Agent is not necessarily of the same type.
I have considered replacing the Base pointer in the Agent definition with an enum, and then retrieving the appropriate Derived class via a map. This does not feel particularly elegant. I also suspect there is a way to do this with virtual base classes, but I am trying to avoid the use of vtables for performance reasons.
Any advice or suggestions regarding a potential solution for my first proposed implementation, or a restructuring to achieve the intended goal would be greatly appreciated. Thank you!
...ANSWER
Answered 2020-May-24 at 15:06CRTP is used for static polymorphism.
If you need runtime polymorphism, there are many ways of achieving that. Virtual member functions with classic OOP inheritance is only one way.
From the excellent "Embrace no Paradigm Programming!", we can see other ways we can do it and how they compare to each other:
If you're only using a known number of derived classes, I'd recommend using a variant
-like data structure. It has static storage, so no unnecessary heap allocations, and all of the storage is abstracted from you.
If you need to export the func()
implementation explicitly, then you'd need to use polymorphic values ("type erasure" on the slides). See the classic Sean Parent talk "Better Code: Runtime Polymorphism". Notice it also uses vtables. To abstract vtables, you'd need to use a more complex struture, like Sy Brand shows in their "Dynamic Polymorphism with Metaclasses and Code Injection" talk.
Also, notice the "OO" performance is not that bad. Virtual member functions aren't that expensive in modern computers, and usually only high-performance/low-latency code cares deeply about this type of optimization.
QUESTION
I'm trying to use C++20 concepts, to start familiarizing with them.
I feel pretty comfortable with easy concepts, for example with the standard concept movable
I can write something like this (in all examples I suppose I'm using namespace std
and I included and any other header needed):
ANSWER
Answered 2020-Apr-26 at 16:17But what is the formal rule behind this form?
The rule (that you correctly guessed your way into) is described in [temp.param]/4:
A type-constraint
Q
that designates a conceptC
can be used to constrain a contextually-determined type or template type parameter packT
with a constraint-expressionE
defined as follows. IfQ
is of the formC
, then letE′
beC
. Otherwise, letE′
beC
. IfT
is not a pack, thenE
isE′
, otherwiseE
is(E′ && ...)
. This constraint-expressionE
is called the immediately-declared constraint ofQ
forT
. The concept designated by a type-constraint shall be a type concept ([temp.concept]).
With examples in the subsequent paragraph:
A type-parameter that starts with a type-constraint introduces the immediately-declared constraint of the type-constraint for the parameter. [ Example:
Community Discussions, Code Snippets contain sources that include Stack Exchange Network
Vulnerabilities
No vulnerabilities reported
Install ModernesCpp
Support
Reuse Trending Solutions
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from over 650 million Knowledge Items
Find more librariesStay Updated
Subscribe to our newsletter for trending solutions and developer bootcamps
Share this Page