Slashdot Mirror


More Effective Use of Shared Memory on Linux

An anonymous reader writes "Making effective use of shared memory in high-level languages such as C++ is not straightforward, but it is possible to overcome the inherent difficulties. This article describes, and includes sample code for, two C++ design patterns that use shared memory on Linux in interesting ways and open the door for more efficient interprocess communication."

280 comments

  1. SysV IPC is obsolete by bogolisk · · Score: 4, Informative

    some1 should tell the authors to rtfm.

    $ man shm_open

    --
    Bogus
    1. Re:SysV IPC is obsolete by KiloByte · · Score: 3, Funny

      The university, ~8 years ago, Concurrent Programming lab:

      (talking about ftok)
      Me: But, what is done to prevent clashes if different programs use the same key?
      Prof: Nothing.
      Me: Eh? That's fucking sabotage. (I used "cholerous", but that was in Polish)
      Prof: And that's why we won't use SysV IPC in subsequent lessons.

      The authors here use a static key of 0x1234...

      --
      The creatures outside looked from Alt-Right to Antifa; but already it was impossible to say which was which.
    2. Re:SysV IPC is obsolete by maxwell+demon · · Score: 5, Funny
      The authors here use a static key of 0x1234...

      Well, that should be a safe choice, because no sane person would use 0x1234, therefore this key is still unused. :-)
      --
      The Tao of math: The numbers you can count are not the real numbers.
    3. Re:SysV IPC is obsolete by Anonymous Coward · · Score: 5, Funny

      0x1234? Amazing! That's the combination on my luggage!

    4. Re:SysV IPC is obsolete by Anonymous Coward · · Score: 0

      try setting the config regietser of a cisco router to 0x1234

    5. Re:SysV IPC is obsolete by El_Muerte_TDS · · Score: 1

      Well, since my 'x' key is broken I always use '01234'

    6. Re:SysV IPC is obsolete by Bloater · · Score: 1, Redundant

      > Well, that should be a safe choice, because no sane person would use 0x1234, therefore this key is still unused.

      Damn, that's the code I have on my luggage. Remind me to change it.

    7. Re:SysV IPC is obsolete by mikeage · · Score: 1

      Well, that should be a safe choice, because no sane person would use 0x1234, therefore this key is still unused. :-)
      I'm not so sure about this -- I'd rather a conflict with a sane person than with the insane one...

      --
      -- Is "Sig" copyrighted by www.sig.com?
    8. Re:SysV IPC is obsolete by javilon · · Score: 1

      static key of 0x1234...

      That is actually the default password (1234) for half of the spanish adsl routers from Telefonica (the incumbent phone company in Spain).

      And most people will never change it.

      And they are accesible from both the internet and wifi (most of them are wifi enabled).

      so go laugh out loud :-)

      --


      When his defense asked, "Which computer has Jon Johansen trespassed upon?" the answer was: "His own."
    9. Re:SysV IPC is obsolete by Ignominious+Cow+Herd · · Score: 1

      Ummm, wrong shm? shmget() shmat(), etc. are SysV IPC. shm_open() shm_unlink() are POSIX. Unfortunate naming maybe.

      --
      Lump lingered last in line for brains, and the ones she got were sorta rotten and insane.
    10. Re:SysV IPC is obsolete by BlurredWeasel · · Score: 1

      So your luggage code is: 4660? Actually, thats a pretty cool way of doing things, come up with a different base and a very simple number, and just convert when you need it.

    11. Re:SysV IPC is obsolete by max0x7ba · · Score: 1
      I agree. The article is crap. Too bad for IBM, cheap indian programmers should continue coding in VB and stay away from Linux/UNIX.

      The main problem is that there is a race between two calls to shm_open(). There should be one call that either opens existing shared memory or creates one atomically.

      Another problem is OO went wild. The authors seem to have read to much of OOP crap and went crazy with needless encapsulation.

  2. Re:snnnoooorrree by claytonian · · Score: 0, Redundant

    ha I feel the same

  3. shmem (soon in Boost!) by Cyberax · · Score: 4, Informative

    There is a great C++ library for shared memory support: SHMEM. It can place complex objects and STL-like containers in shared memory. And it is crossplatform (POSIX and Windows are supported).

    And it will soon (hopefully) be a part of Boost!

    1. Re:shmem (soon in Boost!) by maxwell+demon · · Score: 5, Interesting
      It can place complex objects and STL-like containers in shared memory.

      Depends on your definition of "complex objects".

      From the documentation:

      Virtuality forbidden

      This is not an specific problem of Shmem, it is a problem for all shared memory object placing mechanisms. The virtual table pointer and the virtual table are in the address space of the process that constructs the object, so if we place a class with virtual function or inheritance, the virtual function pointer placed in shared memory will be invalid for other processes.


      Basically, I would have been surprised if they had found a solution for that. But I guess it cannot be portably solved. Instead, the system would have to be prepared for it. I could imagine that objects in a shared library (so the same code is guaranteed to be shared to both processes) could be placed in shared memory, if the compiler/runtime system provided the means for it (say, instead of the pointer to a VMT, it would contain an offset into the constant data section of the shared library, and something to identify the library with, say a system-wide unique active library index which is generated by the dynamic linker).
      --
      The Tao of math: The numbers you can count are not the real numbers.
    2. Re:shmem (soon in Boost!) by Cyberax · · Score: 2, Interesting

      Well, it's possible to use shmem as a very fast method for marshalling of arguments across process boundaries and then use BIL (Boost Interfaces Library) to marshall actual function calls. It will look like Local Procedure Call subsystem in Windows NT.

      You can get virtual functions this way and it will be fast enough but not very "nice", of course.

    3. Re:shmem (soon in Boost!) by guitaristx · · Score: 1

      You could use XML to marshall the objects. It lends itself rather well (if you're careful with how you construct your schema) to dealing with some of the interesting challenges with virtual member functions and variables. It may be overkill in certain situations, but it's probably a simpler way to deal with marshalling than re-working a large object hierarchy so that it contains no virtual functions/variables; i.e. don't reinvent the wheel.

      --
      I pity the foo that isn't metasyntactic
    4. Re:shmem (soon in Boost!) by AuMatar · · Score: 1

      THe shared library would have to be loaded at the exact same memory location for virtual pointers to work. What you're suggesting might be doable, but it would not be very easy, or very efficient.

      There's also the problem of subclasses. If class Foo is in the shared library, but the app makes an instance of Bar (a child of Foo), that overrides any of the virtual functions you'd be in trouble.

      All in all, it just doesn't seem worth the trouble. Just put your data in a stuct with no virtual functions. If you're an OO purist and absolutely need to have your hierarchies and member functions, use a wrapper class with a constructor that takes tghe struct as an input to instantiate the object.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    5. Re:shmem (soon in Boost!) by Anonymous Coward · · Score: 0

      It seems that this would be trivial on a segment based, not paged based system.

    6. Re:shmem (soon in Boost!) by Anonymous Coward · · Score: 0
      It seems that this would be trivial on a segment based, not paged based system.

      Interesting thought, but I don't think it'd work even there. If you had only one codebase for the segment register to point at, it could work. But when there are many shared libraries, you'd have the same problem of the offset of the library within the code segment. Unless you limited the number of shared libraries loaded to the number of segment registers in the hardware, the segment register wouldn't help. I don't think any system does that; it'd be pretty dumb.

      I don't think there's any way to solve this without compiler support at least.

    7. Re:shmem (soon in Boost!) by AuMatar · · Score: 1

      THe only way I can see to solve this is to have libraries decide where in memory they'd be loaded. If a library was loaded at the same place in ram regaurdless of the app that loads it, the addresses would work. The problem here is what happens if two libraries wanted overlapping locations? You'd need a standard for a platform that all compilers agreed to use. Some sort of hash on the library name, perhaps. I'm not sure if the potential advantages outweigh the potential bugs.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    8. Re:shmem (soon in Boost!) by Anonymous Coward · · Score: 0

      This problem is solvable and you don't need compiler support to do it. I would know because I've done it. What you need to do is jettison your OO fetish and go Old Skool.

    9. Re:shmem (soon in Boost!) by Anonymous Coward · · Score: 0

      i actually had to address exactly this issue when i wanted to share a scenegraph data structure among processes via shared memory. scenegraphs make very good use of inheritance and virtual functions, so it was important that the same functionality was retained and that any process sharing the data could use those functions. the solution in the end was to basically reimplement the virtual function pointers myself - each class had an explicit vptr which was set to a local struct storing pointers to static class member functions that took a this pointer as the argument. that way, whichever process you were in, the local function addresses would be used. it wasn't pretty, but it worked...

    10. Re:shmem (soon in Boost!) by AuMatar · · Score: 1

      I'm a C guy, I hardly have an OO fetish. But ok- how would you have 2 processes share a function pointer in C? Using a library is fair game here.

      --
      I still have more fans than freaks. WTF is wrong with you people?
    11. Re:shmem (soon in Boost!) by I+Like+Pudding · · Score: 1

      This is like 10 times more complex and 1000 times slower. Way to kill a good design with XML.

      Again.

    12. Re:shmem (soon in Boost!) by Anonymous Coward · · Score: 0
      THe only way I can see to solve this is to have libraries decide where in memory they'd be loaded. If a library was loaded at the same place in ram regaurdless of the app that loads it, the addresses would work.

      Oh, yeah, that's true. Linux did that before the switch to ELF, IIRC.

      The problem here is what happens if two libraries wanted overlapping locations?

      That's why Linux doesn't do that anymore.

      Some sort of hash on the library name, perhaps.

      For that to work with high probability, you'd need a huge memory space compared to how much you actually intend to use. 2^32 certainly isn't enough. I don't think 2^64 would be, either. UUIDs are 128-bit, and they are single indexes, not the start of long ranges.

    13. Re:shmem (soon in Boost!) by Anonymous Coward · · Score: 0

      While I won't give you the exact answer I will say the best way to solve the problem is to sidestep it. Hint: this problem goes beyond issues with vtables, you can't safely store pointers of any type in shared memory, unless you attach at the same address in all processes. But you don't want to do that because your system would be brittle. That rules out C++ objects. So what are you left with? You think you want a pointer to a function sitting in the same location in memory in two different processes, but you don't really.

    14. Re:shmem (soon in Boost!) by Anonymous Coward · · Score: 0
      But ok- how would you have 2 processes share a function pointer in C?

      You could implement relative addressing in C, rather than using the hardware's. Add extra information indicating what library the function came from. Store the ptrdiff_t between that function and a "reference function". Each caller just adds its own location of the reference together with the ptrdiff_t.

    15. Re:shmem (soon in Boost!) by slamb · · Score: 1
      Well, it's possible to use shmem as a very fast method for marshalling of arguments across process boundaries and then use BIL (Boost Interfaces Library) to marshall actual function calls

      It sounds like what you'd want for that is a message queue. You could write an implementation of messages queues based on shared memory + process-shared mutexes and conditions, but why reinvent the wheel? Linux comes with an implementation.

    16. Re:shmem (soon in Boost!) by maxwell+demon · · Score: 1
      THe shared library would have to be loaded at the exact same memory location for virtual pointers to work. What you're suggesting might be doable, but it would not be very easy, or very efficient.

      Read again what I wrote as example implementation (I've added emphasis to help you understanding):

      instead of the pointer to a VMT, it would contain an offset into the constant data section of the shared library, and something to identify the library with, say a system-wide unique active library index which is generated by the dynamic linker.

      So you see, no pointer in the object.

      And yes, it would be less efficient than a simple virtual function call (it would certainly only be used for objects meant to be shared). Basically there would be a lookup of the unique library index in some table (probably a hash table) to get the base pointer of the library (local to the current process), followed by adding the offset. But I doubt you can get equivalent functionality much more efficiently (apart from obvious optimizations like taking advantage of the fact that in the context of a process the VMT pointer is constant during the life time of the object, and therefore doesn't need to be recalculated if several virtual functions of the same object are called in a row).

      There's also the problem of subclasses. If class Foo is in the shared library, but the app makes an instance of Bar (a child of Foo), that overrides any of the virtual functions you'd be in trouble.

      Of course you only can share objects if you also share their code. I guess it's obvious that for shared objects, the code would also have to be in shared libraries. Although I guess one could even get around this limitation if one designed an executable format with "sharable sections", together with system calls to load those in other programs based on e.g. the process ID. The code for sharable classes, together with the vtbl, would then go into such sharable sections.

      All in all, it just doesn't seem worth the trouble. Just put your data in a stuct with no virtual functions. If you're an OO purist and absolutely need to have your hierarchies and member functions, use a wrapper class with a constructor that takes tghe struct as an input to instantiate the object.

      Maybe it's not worth the trouble. But that was not my point. The point was that you could design a system where it works, but I don't believe a portable implementation is possible.
      --
      The Tao of math: The numbers you can count are not the real numbers.
  4. Re:C++ has bigger memory issues by Cyberax · · Score: 2, Informative

    No, but I think reading about ownership policies and why they almost always make GC unneccessary must be compulsory.

  5. Memory Cache by GoodOmens · · Score: 1, Offtopic
    For those interested the livejournal people released a while ago their source code for memory cache.

    Imemcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

  6. Ever heard of shm_anything? by Anonymous Coward · · Score: 0

    Unix shared memory paradigm has been around for a long time. There is no need to
    re-invent the wheel. BOOST has something, ACE has something, The person that posted
    this article should be modded redundant permanently.

  7. Re:C++ has bigger memory issues by roe-roe · · Score: 1

    More Power to you, back in college my Profs. touted C++ as the shining example of OOPness, curse them I say

  8. Mod parent redundant by Anonymous Coward · · Score: 1, Insightful

    Yup they released it and it sucks. Although somewhat related, a distributed object cache is a solution to a totally different set of problems. Why mention it here?

    1. Re:Mod parent redundant by GoodOmens · · Score: 1, Redundant

      Because its written in C++ ... if it sucks why does Slashdot use it?

  9. Re:C++ has bigger memory issues by ObsessiveMathsFreak · · Score: 5, Insightful

    In fact, forget it; just use an actual OO language instead.

    C++ is an actual Object Oriented language, which is of course half the problem.

    If you mean a pure OO language like Java, in which everything is an object except for primitives and it takes ten classes and wrappers just to read a file, well then C++ isn't exactly an Object Oriented language as such. Perhaps you mean Smalltalk or the like.

    I tell you what though, C++ is still around after all this time. With all the hype surrounding Java, Perl, C#, Python, etc, etc, etc C++ programmers are still there beavering away with the god awful sytax Stroustrup left them with. Even after all the improvments, all the innovation and all the additional research into computer languages, for a hell of a lot of tasks, there is really no real alternative to C++.

    I don't say this as a C++ fanboy, even though I am "somewhat" fond of the language when it is used properly, and not in garbled and unreadable line noise. I say this simply as a statement of fact. There is still no successor to C++.

    I don't want garbage collection so much as I want a cleanup and rationalisation of the syntax. GC would be nice, but forcing more readable code would be even better.

    --
    May the Maths Be with you!
  10. const by hey · · Score: 3, Funny

    I suppose everything marked const could be shared.

    1. Re:const by Leimy · · Score: 1

      The problem is you can still change data in const objects. In some cases it's necessary - hence the "mutable" keyword.

      Once made a class that abstracted a file as an array of records. To be able to make a const version of this that could still read the backing file, I had to have read pointers into the file as "mutable". There is still changeable state, it's just more controlled.

      const is really not a very good guarantee that things won't be changed. The language lets you get around it too many ways.

  11. 10 fold speed improvement - Dekkers mutex ! fast! by Anonymous Coward · · Score: 1, Interesting
    article not perfect yet, much too slow :

    A 10 fold speed improvement in switching context can be done by avoiding OS calls for semaphores and customizing a set of calls for as many comsumer-producers as needed.

    This avoids using any special opcodes or inneficient cache line flushes.

    As long as shared memory is cache coherent, even multiple cpus will work with dekkers 1965 algorithm.

    Here is the complete classic code for one cpu of a dual cpu design system or a dual thread setup :
    INITIALIZATION:
            typedef char boolean;
            volatile boolean flags[2];
            volatile int turn;
     
            turn = AA ;
            flags[AA ] = FREE;
            flags[BB ] = FREE;
     
    ENTRY PROTOCOL (shown for CPU AA ):
    /* Claim the resource */
            flags[ AA  ] = BUSY;
     
    /* Wait if the other process is using the resource */
     
            while (flags[ BB  ] == BUSY) {
     
    /* If waiting for the resource, also wait our turn */
                    if (turn != AA  ) {
     
    /* Release the resource while waiting */
     
                            flags[ AA  ] = FREE;
                            while (turn != AA  ) {
                            }
                            flags[ AA  ] = BUSY;
                    }
            }
     
      EXIT PROTOCOL (shown for CPU AA ):
    /* Pass the turn on, and release the resource */
          turn = BB  ;
          flags[ AA  ] = FREE;
    =

    amazing! unbelievably fast. In fact is optimal.

    Its best if the flags are allocated in their own cachelines, so perhaps pad to 32 bytes on PowerPC for example, and other CPUS might use as few as 16 byte cachlines. This avoids contention and increases coherency for rapid read-writes.

    Add Dekkers mutex as I described and the speed of transactions per second will make your head spin in disbelief even in pathological situations

    How many people know about this? Nobody! I never read about it anywhere. I invented it myself years ago, before I discoverred this year it was called Dekkers, and Dekker beat me to it in 1965. I tried unsuccessfully, verbally, to get a Phd in comp Sci with embedded management experience to believe me it is 100% sound.... argued for 40 minutes. The guy never had a clue. No wonder that his company's stock is down over a couple billion in market cap since the argument.

    Lets not forget the past. Some algorithms are worth remembering.
  12. This is nothing new by Anonymous Coward · · Score: 4, Interesting
    You've been able to do this for a while using process shared mutexes and condition variables which allow you to do the same things you could do with pthreads and shared memory. The tradeoff is you get better performance avoiding syscalls to do IPC but it's less robust. If you get a segfault, you have to assume that the shared memory is in an unknown state and either shutdown or restart everything. The other processes can (or will be able) to detect this using once robust futex support is in Linux. Idiot programmers will of course ignore this and continue to use the corrupted memory anyway just like they do now with sysV semaphores used as mutexes with the SEM_UNDO option to allow the semaphore to auto reset if a process exits without resetting it.

    Anyway, old stuff. Wake me up when you start talking about the newer tricks with shared memory.

    1. Re:This is nothing new by Anonymous Coward · · Score: 1, Informative

      If you get a segfault, you have to assume that the shared memory is in an unknown state and either shutdown or restart everything.

      Actually, you don't. There are multiple ways of handling this. Three approaches are critical sections, journalling, and partial rebuilds.

      If you get a segfault in some function, memory does not start magically going haywire; it is not changed after that point. Another process can attach to your shared memory and look at the data structure that was being manipulated and repair it. If the operation is journalled, just replay it (of course you have to fix whatever the NULL pointer is). Or you can avoid full journalling by doing a mini-journal and if interrupted during a write operation, rebuild just that one data structure. If using critical sections, if interrupted, revert to a previous copy of the data. These approaches work not just for segfaults but for kill -9, power going out, etc.

      Multiple processes plus shared memory is a much more robust solution than threading. For one, pthreads itself has historically been a source of much bugginess, like Sendmail. For another, if one thread dies they all die; with separate processes, that isn't the case. Just add locks/mutexes to your shared data structures. This also simplifies some things, because if it's NOT in shared memory, it's local to only one process, so you don't have to lock every single thing.

    2. Re:This is nothing new by Anonymous Coward · · Score: 0

      The problem is shared memory state is for all practical purposes undefined after a segfault since you can't guarantee the error occurred at the segfault. It could have occurred earlier. You're perfectly welcome to go on comp.programming threads and state that you can recover from segfaults. Or you can save yourself some public humiliation and just google for it.

  13. Re:C++ has bigger memory issues by nagora · · Score: 1, Flamebait
    I tell you what though, C++ is still around after all this time.

    Mostly because it allows sloppy, C-style, programming which is easy. It also leaks like a sieve most of the time and has all the security problems seen in C. It doesn't HAVE to but its design means that it does. And it's ugly as hell.

    Easy programming languages always hang around longer than they're needed because most programmers, sad to say, are uninterested in quality and very interested in meeting deadlines.

    There is still no successor to C++.

    That may be true, but it doesn't make C++ any better.

    TWW

    --
    "Encyclopedia" is to "Wikipedia" what "Library" is to "Some people at a bus stop"
  14. CML by putko · · Score: 3, Informative

    For concurrent applications, it is hard to beat Reppy's CML.
    http://portal.acm.org/citation.cfm?id=113470

    In particular, the things you synchronize on are first-class. Also you can speculatively send/receive things. Normal "select" is only for reading. You don't have to manage your memory either.

    There are other concurrent languages, but CML is nice in that it has a formal semantics, so unlike typical languages like "C", "C++", Erlang or Java, a program has a meaning other than "whatever the program does when I run it."

    You can implement the primitives of CML in your favorite higher-order language, so you don't have to be limited by ML. That's what's in Reppy's book.

    A proper implementation can achieve speeds that are about 30x faster than pthreads for typical tests like "ping/pong".

    --
    http://www.thebricktestament.com/the_law/when_to_s tone_your_children/dt21_18a.html
    1. Re:CML by Ulrich+Hobelmann · · Score: 1

      First of all, I want to flame you for making propaganda for the ACM from hell. Yes, some people don't want to pay money for a paper that was probably at least partly funded by taxpayers.

      CML is nice (as is SML to begin with), but I assume the reason it's faster than pthreads is that it doesn't use OS-level concurrency (just like Oz or Erlang). As a result it probably can't take advantage of multiple CPUs.

      By the way, CML's memory use is probably the opposite of the mentioned C++ technique: everything dynamically allocated in a garbage-collected system.

  15. Hardware-enforced sharing: OLD HAT by VernonNemitz · · Score: 4, Interesting

    Quite a few years ago, there was a brief popularity of something called VRAM (video ram) that had memory cells specifically designed with one input line and TWO output lines. The idea was that the part of the hardware needing to construct an image for the screen ONLY needed to read memory, while the system responsible for creating the image needed both read and write access. Ever since then, I've wondered why they don't use this kind of memory in multi-processor systems, for communication between processors, such that Processor A has read/write access to a block of VRAM, to give info to Processor B (it has read-access only), while Processor B has read/write access to a different block of VRAM, to give info to Processor A (it has read-access only).

    1. Re:Hardware-enforced sharing: OLD HAT by TheRaven64 · · Score: 3, Informative

      Because it's a really ugly hack that only works in a specific domain. If the frame buffer is being read and updated at the same time, you might get some screen corruption. This is irritating, but not really a problem. If a general piece of memory is being read from and written to at the same time, then the reading process gets garbage data. This means that you need to put locks around your memory (which you do anyway) to prevent this, which eliminates the advantage of the second read line.

      --
      I am TheRaven on Soylent News
    2. Re:Hardware-enforced sharing: OLD HAT by LiquidCoooled · · Score: 1

      I would imagine that such a system could be simple in a dual cpu setup and from a logical point of view would be nice to do on a process basis.

      However, the system wouldn't appear to scale too well. The overheads of scanning every other read only block would soon mean a reduction in the work done, not to mention the security nitemare that would unfold.

      IPC using a shared memory model means each entity only has to check his own event queue and doesn't need to bother about anything else.

      Of course, as per my sig I might be completely wrong.

      --
      liqbase :: faster than paper
    3. Re:Hardware-enforced sharing: OLD HAT by Waffle+Iron · · Score: 1
      Ever since then, I've wondered why they don't use this kind of memory in multi-processor systems

      IIRC, the video port of a VRAM wasn't really random access. It would load an entire row of the RAM array into an output buffer, and then you had to shift out the columns serially. This avoided conflicts on the address bus, and it works fine for refreshing a video display, but it isn't at all suitable for general multiprocessor use.

      I seem to remember that you could buy true dual-ported static ram at one time, with 2 address buses and 2 data buses, but it was hideously expensive.

    4. Re:Hardware-enforced sharing: OLD HAT by velco · · Score: 1

      Because it's a really ugly hack that only works in a specific domain. If the frame buffer is being read and updated at the same time, you might get some screen corruption.

      Utterly wrong, of course. There's only one writer. You don't expect the screen (actually, the DAC) will suddenly start writing to the frame buffer, do ya?

    5. Re:Hardware-enforced sharing: OLD HAT by ConceptJunkie · · Score: 1

      You could get half of the old data and half of the new data, right?

      --
      You are in a maze of twisty little passages, all alike.
    6. Re:Hardware-enforced sharing: OLD HAT by Anonymous Coward · · Score: 0

      In VRAM, an entire row of memory gets copied into a buffer that is read sequentially by the DAC. There is a lock in hardware for this, and dobviously, the DAC can get outdated data, namely anything that has been changed in the row after it was copied.

    7. Re:Hardware-enforced sharing: OLD HAT by arkanes · · Score: 1
      This is basically what happens when you get tearing - data changes halfway between a screen refresh. Old-school video game authors had went to enormous lengths to make sure that they got data into the framebuffer in sync with the monitors scanlines.

      There was some old Atari game that needed some extra memory and actually stored it in the framebuffer, pulling it out as it needed it just ahead of the scan rate. Crazy low level programming.

    8. Re:Hardware-enforced sharing: OLD HAT by ConceptJunkie · · Score: 1

      Crazy low level programming

      Everything I've ever read about the Atari makes it sound like just one step above the story of "Mel" from the Jargon file.

      It sounds like a fascinating challenge, but I think I wait until someone pays me to learn it. ;-)

      --
      You are in a maze of twisty little passages, all alike.
    9. Re:Hardware-enforced sharing: OLD HAT by RAMMS+EIN · · Score: 1

      IIRC, VRAM exactly prevents this from happening; the read port that is used to get the pixel data is kept stable, regardless of if a write to the cell is going on. It was the old, plain DRAM based cards that would get snow on the screen when you didn't synchronize your updates with the vsync. I could be wrong, though; I never really cared about the snow anyway.

      --
      Please correct me if I got my facts wrong.
    10. Re:Hardware-enforced sharing: OLD HAT by velco · · Score: 1

      Probably not. All display addapters are using double-(tripple-, quad-) buffering anyway.

  16. Re:Microsoft code? by Curien · · Score: 1

    I consider the backwards comparison to be good C style. It turns a certain broad class of typo from a silent logic error into a compiler error. How many times have you seen

        if(x = foo() != -1)

    when the programmer meant

        if((x = foo()) != -1)

    ?

    If you write your comparisons with the constant first, the compiler will tell you. In particular,

        if(-1 != x = foo())

    results in a compile-time diagnostic. It's not about "being unfamiliar with C++ syntax". Quite the opposite, someone who writes that way is so familiar with C and C++ syntax that they know how to avoid the common mistakes without batting an eyelash.

    --
    It's always a long day... 86400 doesn't fit into a short.
  17. Re:10 fold speed improvement - Dekkers mutex ! fas by Anonymous Coward · · Score: 1, Informative

    in my above example i noticed slashcode converting some single ascii space white space into

    AMPERSAND POUND-SIGN 160 SEMICOLON

    just swap those back to spaces.

    "POUND-SIGN" is defined as octothorpe, not pound-sign the english monetary unit glyph

    I would have typed OCTOTHORPE above but i was just letting usa people understand a little more clearly

    anyway ignore the AMPERSAND POUND-SIGN 160 SEMICOLON ... the source code is correct

    i wanted to post this earlier, but slashcode crap makes me wait FOREVER to post a correction! What crap. its been 6 minutes and it says "Slow Down Cowboy! It's been 6 minutes since you last successfully posted a comment" I wonder why engineers like me even bother trying to help out on slahdot anymore.

  18. Re:Microsoft code? by maxwell+demon · · Score: 2, Informative

    Doesn't MS code use CWhatever? I guess the author is coming from a Java background (I for Interface).

    BTW, the very first file is not valid C++: All identifiers which contain double underscores are everywhere and under all circumstances reserved for the implementation. This also includes __COMMON_H__. Change it to e.g. COMMON_H to get valid C++.

    Well, at least his main function returns int.

    --
    The Tao of math: The numbers you can count are not the real numbers.
  19. Re:Microsoft code? by Erik+Hensema · · Score: 2, Insightful

    I consider compiling with -Wall good style, which warns you when doing an assignment used as an expression. if ((a = 1)) supresses the warning, assuming the coder knows what he's doing.

    --

    This is your sig. There are thousands more, but this one is yours.

  20. Re:Microsoft code? by Tony+Hoyle · · Score: 1

    Almost never... since any half decent compliler will spit out a warning at least (and no shipping code should compile with warnings).

  21. Re:Microsoft code? by maxwell+demon · · Score: 1
    consider the backwards comparison to be good C style. It turns a certain broad class of typo from a silent logic error into a compiler error. How many times have you seen

            if(x = foo() != -1)

    when the programmer meant

            if((x = foo()) != -1)

    ?

    The programmer actually meant:
    x = foo();
    if (x != -1)
      ---
    --
    The Tao of math: The numbers you can count are not the real numbers.
  22. Re:C++ has bigger memory issues by LarsWestergren · · Score: 1, Offtopic

    Java, in which everything is an object except for primitives and it takes ten classes and wrappers just to read a file,

    Eh?

    File inputFile = new File("temp.txt");
    FileReader in = new FileReader(inputFile);

    Or if you want to use the new IO library from 1.4 which gives you memory mapping and locking on sections of files,

    FileChannel in = new FileInputStream("temp.txt").getChannel();

    --

    Being bitter is drinking poison and hoping someone else will die

  23. Doors by Anonymous Coward · · Score: 5, Interesting

    I'm surprised no-one has mentioned Solaris Doors. Doors is an IPC mechanism whereby the first process (client) can hand off any residual time in its timeslice to the second process (server) resulting in short IPC calls running much less time as there is no discarded timeslice time and no wait for the server process to be scheduled (since it uses the client's timeslice).

    1. Re:Doors by Anonymous Coward · · Score: 0

      I'm surprised no-one has mentioned Solaris Doors.

      What? And cramp IBM's style? You must be new round here. This is IBM's fortnightly PR fluff piece. We like IBM and hate Sun.

    2. Re:Doors by Anonymous Coward · · Score: 1, Interesting
      Except for the time slice trickery, you can do everything a door call can do with Unix domain sockets. And even there you could probably bump the priority of the threads in the thread pool to get the same effect. Something that would really be nice would be cross address call like IBM mainframes have. No context switching except for the memory space switch. In contract, Solaris door calls require a syscall and context switching to and from the door process thread pool. Plus some cross memory space copying of input and output data. Not exactly cheap.

      I was proposing on comp.programming.threads process level smart pointers that would let you use read only shared segments for IPC. Read only meaning more robust. So for example you could implement a NSCD (name services cache daemon) which would allow in cache host name resolution to run in only microseconds or less which is a lot faster than a door call could ever be. But not a lot of interest so far so the idea is currently shelved.

    3. Re:Doors by Foolhardy · · Score: 2, Interesting

      That sounds like the same as NT's event pairs, used to implement Quick LPC. An event pair consists of a high and a low event. The server thread waits on the high event and the client thread waits on the low event. Only one event can be signalled at one time, and two software interrupts are provided to toggle the event pair's state: interrupt 0x2C calls the function KiSetLowWaitHighThread() and interrupt 0x2B calls the function KiSetHighWaitLowThread(). When one of these is called and another thread (in another process) is waiting on the other event, the kernel schedules the other thread immediately, continuing the same timeslice of the calling thread. Transfer of data is done through a shared memory section mapped to both processes. Quick LPC was introduced in NT 3.51 to make the out-of-process GUI server faster. Apparently Microsoft didn't think it was fast enough, so they moved much of the GUI server into kernel mode in NT4.

      For more information, scroll down to Quick LPC in Local Procedure Call from Undocumented Windows NT.

  24. Comments on comments by Tzinger · · Score: 2, Insightful

    Too many people here are willing to make inane useless comments about honest work efforts. If you have a better way, offer it. If you merely want to say something nasty about someone else's work, save it for the coffee house.

    --
    "If all the American people want is security, let them live in prisons." Eisenhower
    1. Re:Comments on comments by Anonymous Coward · · Score: 0

      Sorry, no, that attitude doesn't fly. Maybe it has its place in special education, but in the real world, it's stupid to think that something is worthwhile because, even though it's shit, the person who did it tried really hard. Sorry, it's still shit, and this isn't special ed where retards need to be encouraged.

    2. Re:Comments on comments by Fordiman · · Score: 1

      This isn't a coffee house?!

      *looks down at his cup* Damn. I must've come to the wrong place.

      --
      110100 1101000 1101000 1100110 0 1101111 1101000 1100011 1
  25. Misuse of 'synchronous' by Anonymous Coward · · Score: 0

    "Now let's look at using shared memory and caching of events for interprocess communications. If the events are cached within the shared object, they can be fired later. The receiving process will have to query the shared object for events. Thus, by sticking to a synchronous model, interprocess communication can be achieved. This is the motivation behind developing the following design pattern."

    Que? How is that different from an asynchronous message event que? I think they've misused the word synchronous. Presumably the calling process is not waiting for the return from the process it called, so the two processes are running asynchronously. So this is just asynchronous event message passing.

  26. Re:C++ has bigger memory issues by CyricZ · · Score: 1

    If you mean a pure OO language like Java, in which everything is an object except for primitives ....

    Your statement is contradictory. All types are objects in a pure OO language. Yet Java's primitives are not. Thus Java is not a pure object oriented language.

    --
    Cyric Zndovzny at your service.
  27. Re:C++ has bigger memory issues by theCoder · · Score: 4, Interesting
    C++ already has a garbage collector. Just allocate your objects on the stack instead of the heap:
    void foo()
    {
      SomeObject obj;
     
    // other code
     
    // poof -- obj is deallocated automatically, even if an exception is thrown
    }
    I work on a project that has tens of thousands of C++ classes, and very few "new" and "delete" operations (more "new" than "delete" because we have a class that manages reference counting like a heap garbage collector would do).

    People who think they always need to "new" objects in C++ have spent way too much time using Java.

    Here's another hint -- pass objects to functions as const references:
    void foo(const SomeObject& obj)
    {
    // code
    }
    This way, a copied object isn't allocated for the passing (no memory at all is in fact allocated). The biggest drawback is you can only call "const" methods on the object, but this is outweighed by not using pointers. Not that I don't like pointers, they just increase the complexity and should be used prudently. And as my .sig says, be sure to free those mallocs!

    --
    "Save the whales, feed the hungry, free the mallocs" -- author unknown
  28. Re:10 fold speed improvement - Dekkers mutex ! fas by Anonymous Coward · · Score: 0

    That's funny. This was one of the first synchronization algorithms we learned in my operating systems class.

  29. Re:C++ has bigger memory issues by Anonymous Coward · · Score: 1, Insightful

    That everything is an object in Java except for the primitive types are such a cop out by Sun. Think of all the hacks that result just from that. In Smalltalk, everything is an object even the primitive classes!

    As for why C++ is still being used, it is a more type-safe C at the very least. It is nice to be able to do function overloading and declare variables anywhere. And once one gets past the horrible syntax, amazing things can be done/achieved with C++ templates.

  30. Re:10 fold speed improvement - Dekkers mutex ! fas by Yokaze · · Score: 1

    > How many people know about this? Nobody!

    Only those, which know of Futexes.

    --
    "Between strong and weak, between rich and poor [...], it is freedom which oppresses and the law which sets free"
  31. Re:C++ has bigger memory issues by Anonymous Coward · · Score: 0

    Can someone explain why parent is +1 insightful and not -1 troll? (or flamebait)?

  32. Re:C++ has bigger memory issues by jimktrains · · Score: 1

    Or in C

    FILE stream = fopen( "crt_fopen.c", "r" );

    The only way to read the filechannel is a bytebuffer. Has anyone ever used them? I had to once and it sucked....

    FileReader (or BufferedInputStream) are still awkward because tehy use byte and string arrays. Those really are hard to work with w/o doing conversions in java, where in C the char arrays are usfule w/o conversion. I have always found C and PERL IO better than Java's.

    --
    "You will do foolish things, but do them with enthusiasm." - S. G. Colette
  33. Re:Microsoft code? by Curien · · Score: 1

    I consider using ((x=1)) to supress the warning to be even worse than leaving the warning in.

    --
    It's always a long day... 86400 doesn't fit into a short.
  34. Re:C++ has bigger memory issues by Jamu · · Score: 1

    I can see no reason for making mandatory garbage collection part of the C++ language. It wouldn't make it one bit more useful; C++ doesn't prevent you from using garbage collection in your programs. If C++ needs a garbage collector(s) then it (or they) should go into the standard library (if anywhere) and not the language itself. Restricting the use of a language will never make it more useful.

    --
    Who ordered that?
  35. Re:Microsoft code? by Anonymous Coward · · Score: 0

    It's not about "being unfamiliar with C++ syntax". Quite the opposite, someone who writes that way is so familiar with C and C++ syntax that they know how to avoid the common mistakes without batting an eyelash.

    The point is, it's only a common mistake for those unfamiliar with the language.

    For a pro, it's as common a mistake, as writing if x:=7 in Pascal.

    if(7==x) is a way to prevent a beginners mistake, by ruining readability. For programmers above first semester, readability is way more important than avoiding beginners mistakes that they shouldn't be making in the first place.

  36. Re:10 fold speed improvement - Dekkers mutex ! fas by Anonymous Coward · · Score: 5, Informative

    Yes, some algorithms are worth remembering...

    This one is worth remembering as one to avoid -- it's based on the idea of a busy-wait. Look at the while(test) { /* do nothing */ } loop and outer while loop. This should not be done. Semaphores might be slower in the specific case, but overall system performance will benefit from using best-practices.

    There's a reason this algorithm lies in rest in academic journals: it's only useful as a teaching tool.

  37. Re:C++ has bigger memory issues by strider44 · · Score: 1

    You've forgotten the exception catcher.

  38. Re:Microsoft code? by Curien · · Score: 1

    I can logically deduce from your statement that almost all the code you ever see is production code. In which case, I don't think your opinion matters very much.

    --
    It's always a long day... 86400 doesn't fit into a short.
  39. Fanboy mods... by mangu · · Score: 2, Informative
    why parent is +1 insightful and not -1 troll? (or flamebait)?


    There are some subjects that draw fanboy clubs here in /.


    Some examples: Java, AMD, Apple, Ruby.


    Try criticizing any of them here, you'll be down-moderated to (-1) pretty quickly. OTOH, praise any of those and you'll get moderated up, no matter how stupid or inconsistent the comment is.

    1. Re:Fanboy mods... by bogolisk · · Score: 2, Informative

      you forgot xxxBSD and Gentoo.

      --
      Bogus
    2. Re:Fanboy mods... by Blakey+Rat · · Score: 1

      Don't forget Nintendo, in the Games section. I think that one's worst of all... they don't even pretend to be unbiased.

    3. Re:Fanboy mods... by Anonymous Coward · · Score: 0

      Also, whine about getting modded down and get modded up.

  40. Re:C++ has bigger memory issues by CosmeticLobotamy · · Score: 1

    It's been a while since I've used C++, so maybe the part of my memory that held the reason why this is about to be a stupid question was repurposed, but why are you passing it as a const reference instead of just a reference? It still won't make a new copy of the object, right? But then you aren't stuck with only const methods.

  41. Re:C++ has bigger memory issues by Rakshasa+Taisab · · Score: 1

    C++ is a multi-paradigm programming language, and is still evolving. (Rather, should we call it ID?)

    It supports procedural, OO and functional programming, the last still needs improvement. Contract programing is in the works, and will amongst other things alleviate all those nasty template error messages. Fine-grained GC is already in TR1 and should be available from major compilers pretty soon. It is interesting to note that GC is being done in the standard library, unlike C# which does it in the core language. Some would propably claim this means C++ doesn't have "true" GC support, rather than realizing it is just a different approach to the problem.

    C++ won't die as long as it keep evolving, even though it is a rather glacial evolution. So to say it doesn't follow new research into computer languages is to ignore the progress that does happen.

    --
    - These characters were randomly selected.
  42. Re:Microsoft code? by Curien · · Score: 1

    An if perhaps wasn't the best example. In a while, though, it can avoid duplicate code.

    --
    It's always a long day... 86400 doesn't fit into a short.
  43. Re:10 fold speed improvement - Dekkers mutex ! fas by Anonymous Coward · · Score: 0

    This thread goes out to all the HTML turned PHP hackers who whine that Comp Sci is a useless major


    Nothing against PHP or HTML of course

  44. Re:C++ has bigger memory issues by Dan+Ost · · Score: 1

    So does that make Python a pure OO language since you can inherit from anything?

    --

    *sigh* back to work...
  45. Re:C++ has bigger memory issues by abdulla · · Score: 1

    I have to say, on average for projects I've had the opportunity to view code for, C++ code is far easier to understand and grasp than the equivalent C code. You can instantly see the structuring of the code and how it correlates. Whereas often the equivalent code in C isn't as clear. Ofcourse this is usually a programmer problem more than anything, since I often see people less structured in their C usage.

  46. Re:Microsoft code? by Curien · · Score: 1

    In what way is "EOF != (c = getc(stdin)) less readable that "(c = getc(stdin)) != EOF"?

    --
    It's always a long day... 86400 doesn't fit into a short.
  47. Re:10 fold speed improvement - Dekkers mutex ! fas by tfmkayaker · · Score: 1

    MOD the parent of this comment up!!!

  48. Re:10 fold speed improvement - Dekkers mutex ! fas by Anonymous Coward · · Score: 3, Insightful

    IMHO this algorithm is not a panacea because :

    - It does busy waiting. If one thread holds the 'mutex' for a long time, the other thread will take a lot of CPU for nothing.
    If you really need to take the resource as soon as it is available without giving up the proc, then have a look at "spin locks".

    - It is not very scalable.
    First, you need one version of the algorithm for mono proc one for bi proc, etc. Of course you could put them all in a shared lib and select one at runtime.
    Second, the algo seems to be O(N), N being the number of processors. Therefore the algo slows down when the number of proc increases.

    - And last: it is unclear to me how you pass turn when there are more than 2 procs involved. Does this algorithm work when there is more than 2 processors ?

  49. alternative in the making... by clayasaurus · · Score: 1

    The D programming language is shaping up to be a nice alternative.

    1. Re:alternative in the making... by arkanes · · Score: 1

      D is a fantastic language and the only modern language that even acknowledges that RAII is awesome, and that GC solves only one resource management problem. Lack of resource management tools (memory is *not* the only resource!) and determentistic finalization are sever weaknesses in Java.

  50. Re:10 fold speed improvement - Dekkers mutex ! fas by Anonymous Coward · · Score: 0

    you fool! Duh!

    Are you an idiot! naturally that is where you would implement sleeping or thread suspension! the point is to show the relevant FAST part.

    The routines used by linux and even BSD historically (before 1994) were slow, and the current stuff is still not as fast as this, by far.

    naturally you would implement your sleep or poll in that section, if more than a microsecond or two elapsed.

    the code is a skeleton demonstrating that the massive hit hidden in special opcodes or special os calls can be avoided.

  51. Re:C++ has bigger memory issues by qray · · Score: 1

    I would have no problem with making a collector as a backup mechanism. Unfortunately Java, C#, etc. provide no other means for managing memory. This assumes that the algorithm is always superior to the engineer. Unfortunately in some cases that's not true and prevents the use of Java, C#, and similar languages.

    The other issue is that many of these VM's assuming they're the only thing running on the system. They'll happily consume RAM until available RAM gets low, starving other applications needlessly.

    Then there's the issue that they just don't do real well when memory gets paged out. The current crop of mark/sweep generational algorithms don't cut it in many situations. They cause excessive page swapping.

    What I want is something that watches my back, but doesn't get in the way. It should allow me to grab the reins and take control when I know more than the GC algorithm does.

    I wish I had a moderation point left, I'd vote for troll ;-) -
    Q

  52. Re:C++ has bigger memory issues by LarsWestergren · · Score: 1

    You've forgotten the exception catcher.

    No, that was actually quite deliberate. When people say they can open and read a file in Perl or C with only one line, they haven't included any error handling, so I think it's only fair to do the same here.

    --

    Being bitter is drinking poison and hoping someone else will die

  53. Re:C++ has bigger memory issues by ObsessiveMathsFreak · · Score: 1

    C++ code is far easier to understand and grasp than the equivalent C code. You can instantly see the structuring of the code and how it correlates.

    Oh good gods yes! As an example for how all over the place c code can get, try looking into the mplayer source tree. Men have but gazed upon its grim pointer laden facade, and gone instantly mad. Mplayer.c is 4000 lines long!

    --
    May the Maths Be with you!
  54. Re:C++ has bigger memory issues by Jamu · · Score: 1

    C/C++ doesn't prevent you from coding secure, leak-free programs. All it does is shift the responsibility for security and memory management from the language to the programmer. If you're a sloppy programmer then, yes, you need a better language than C/C++.

    --
    Who ordered that?
  55. Re:Microsoft code? by WraithRealm · · Score: 1

    IWhatever is the hungarian notation for interfaces. CWhatever is for objects that are complete classes.

    --
    I aim to misbehave.
  56. Re:C++ has bigger memory issues by Curien · · Score: 2, Informative

    Two reasons:
    a) The called function _cannot_ modify the argument. This becomes important to the code surrounding the function call.
        T x(...);
        foo(x); // did x get changed?

    If foo is declared "void foo(T const&)", then you *know* that x has not changed. If instead it's declared as taking a plain reference, you can't know.

    b) You can pass const objects or objects with limited lifetimes.

        foo(T()); // legal if foo takes a T const&, but not a T&

    --
    It's always a long day... 86400 doesn't fit into a short.
  57. What does it take to be a successor? by Skapare · · Score: 1

    So, what would it take to satisfy your criteria on being a proper successor to C++, if none of C#, Java, Pike, Python, and many others are unable to qualify?

    --
    now we need to go OSS in diesel cars
    1. Re:What does it take to be a successor? by ObsessiveMathsFreak · · Score: 1

      So, what would it take to satisfy your criteria on being a proper successor to C++, if none of C#, Java, Pike, Python, and many others are unable to qualify?

      Isn't it obvious? Something better!

      --
      May the Maths Be with you!
    2. Re:What does it take to be a successor? by swillden · · Score: 1

      So, what would it take to satisfy your criteria on being a proper successor to C++, if none of C#, Java, Pike, Python, and many others are unable to qualify?

      One of the overriding goals behind the design of C++ was that it had to be as efficient as C. Stroustrup made many design decisions to ensure that C++ is never slower than C except in a few cases where the programmer makes a decision to invoke one or more of a small set of features that simply cannot be provided without overhead, and even there he tried to make the overhead as small as possible. He succeeded, but only at the cost of considerable language complexity.

      You can debate about whether or not as-efficient-as-C is a good requirement for a high-level OO language, but I think anything that could be considered C++'s successor would have to meet it.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    3. Re:What does it take to be a successor? by mrshoe · · Score: 1

      Unfortunately, this common misconception just isn't true. C++ is not as efficient as C.

      This according to the Debian language shootout.

      The fact is that D is more efficient and has a far better syntax. C++ is an ugly language that has survived on hype and misconceptions. It's a shame, really.

      --
      There are two types of people in this world: those that categorize other people and those that don't.
    4. Re:What does it take to be a successor? by tjstork · · Score: 1

      In the shootout, what are they comparing. Actually, why is C++ slower than C? I know that going through virtual methods will always be slower than straight up function calls, but what else is going on in there?

      --
      This is my sig.
    5. Re:What does it take to be a successor? by Skapare · · Score: 1

      Certainly those languages leave a lot of room for "something better". But what particular criteria would make a language better? I suspect not everyone will rank these criteria the same way (hence we get so many languages). For example, I happen to like the C syntax and that means I find Pike a good choice. Still, even Pike has room to be improved on. I happen to not like C++ at all.

      --
      now we need to go OSS in diesel cars
    6. Re:What does it take to be a successor? by swillden · · Score: 1

      This according to the Debian language shootout.

      Those benchmarks are interesting to analyze but they're meaningless for really evaluating language performance. The larger (and more powerful) C++ standard libraries give it a significant penalty in such tiny program comparisons, but those same libraries often give it a considerable advantage in real programs (consider this as an example of another trivial program where performance is hugely in C++'s favor, due entirely to good libraries and the power of templates).

      C++ code is not appreciably different from C code except where specific constructs are used, and the run-time costs there are small and quantifiable while the programmer efficiency gains can be enormous. C++ is, in general, as fast as C.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    7. Re:What does it take to be a successor? by mrshoe · · Score: 1

      I wouldn't go as far as to say that microbenchmarks are meaningless. Most of the linked page on the shootout site deals with the "every application is different" issue. This becomes very important when you realize different languages were designed for different tasks and should therefore be used in different situations. However, when comparing C and C++, which are relatively close in performance (as opposed to C and Python), I've found the shootout to be a pretty good estimate of general performance because they do have 21 different test cases.

      To cite a personal project that backs up my claims, I have ported my raytracer Sol to 4 languages (C, C++, D, and Python). The C++ port was slower than the D port and much slower than the C port. The performance hit is not only due to specific constructs (such as virtual methods, as mentioned above), but also to C++'s tendancy to perform lots of excess memory copying when an instance is passed as a function parameter or when the assignment operator is used. Sure, the programmer can do much to avoid this useless copying, but the language doesn't really encourage it at all (unlike D, Java or Python which use pointers under the covers instead of copying objects).

      At any rate, I've certainly found C++ to be much slower in my applications and I've found the shootout to be a decent guage of language/compiler performance. My biggest gripe with C++, however, is certainly not performance. In fact quite the opposite is true. I merely wanted to debunk the notion that we have to put up with C++'s ugliness because it out-performs the alternatives.

      --
      There are two types of people in this world: those that categorize other people and those that don't.
    8. Re:What does it take to be a successor? by swillden · · Score: 1

      C++'s tendancy to perform lots of excess memory copying when an instance is passed as a function parameter or when the assignment operator is used. Sure, the programmer can do much to avoid this useless copying, but the language doesn't really encourage it at all

      I read the above as "A programmer who doesn't know C++ tends to write less efficient code". There's no doubt that C++ requires a heavy investment in learning, not just of syntax and features but of styles and proper usage as well. Avoiding unnecessary copies is one of the first things you should learn on the way to becoming a decent C++ programmer.

      My biggest gripe with C++, however, is certainly not performance. In fact quite the opposite is true. I merely wanted to debunk the notion that we have to put up with C++'s ugliness because it out-performs the alternatives.

      That is a reasonable point, at least in the common programming environments. The languages you mention (except, perhaps, D -- I have to admit that I'm really not familiar with it) don't work well at all in bare-metal programming. IMO, that prevents them from being considered true "successors" to C++; they may be better choices for some environments but they simply don't have the broad applicability of C++.

      Looking at the Wikipedia entry describing D, I'll have to give it a look. It sounds very good. The fact that the language changes from time to time means it's probably not wise to embark on any large projects, though :-)

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
  58. Re:C++ has bigger memory issues by nagora · · Score: 1
    You make a lot of good points but on balance, I'd far rather have a GC than not. Most of the time I want to work with objects that's exactly what I want to treat them as: objects, not memory allocations which have to be tracked as part of the design. That breaks down sometimes, sure, but that's when your "backup mechanism" would come into place. GC without a backup is annoying but having neither is just stupid and the evidence is all around us in the millions of C++ programs which leak memory.

    I wish I had a moderation point left, I'd vote for troll ;-)

    Me too.

    TWW

    --
    "Encyclopedia" is to "Wikipedia" what "Library" is to "Some people at a bus stop"
  59. Re:C++ has bigger memory issues by linuxcoder · · Score: 1

    It also leaks like a sieve most of the time and has all the security problems seen in C

    WRONG! Memory leaks and security problems are not the fault of the language. The programmer is solely to blame. Proper freeing of memory and sane buffer management goes a long way to creating good, secure code. Sure, other languages may take care of this for you, but you can do the same in C/C++ with wrappers if you are too lazy to handle it yourself.

  60. Re:Microsoft code? by munderwo · · Score: 1

    a) You're not impressing anyone by trying to cram your program into a single line of text.

    b) If you're so smart you identify the constants and re-order your expression accordingly, then why aren't you smart enough not to avoid the mistake in the first place?

  61. Re:C++ has bigger memory issues by TheGavster · · Score: 1

    The difference of course being that the C/C++ will still compile, and the Perl actually puts the error handler on the same line:

    open my $filehandle, '', 'filename' or die 'omfgwtfbbq!';

    --
    "Because Science" is one step from "Because old book". Try "Because of my experiment testing my falsifiable assertion".
  62. Re:C++ has bigger memory issues by pslam · · Score: 1
    I think getting a garbage collector mandated as part of the language would be a much bigger step to making C++ a useful choice.

    You say that as if C++ isn't in use by the vast majority of software houses on the planet, and rather successfully for that matter.

  63. Re:10 fold speed improvement - Dekkers mutex ! fas by at_18 · · Score: 3, Informative

    I tried unsuccessfully, verbally, to get a Phd in comp Sci with embedded management experience to believe me it is 100% sound.... argued for 40 minutes. The guy never had a clue.

    The guy had a clue. Your algorithm is a busy-wait loop, so your CPUs will be maxed at 100% while waiting, and the thread will be pushed by the scheduler to lower priority, and so on...

  64. Re:Microsoft code? by Curien · · Score: 1

    a) The technique is commonly used to avoid duplicate code in a loop with priming read. Duplicate code is worse than a slightly more complicated line, as it doubles the work required by a maintenance programmer.

    b) One is a habit, the other is a typo. I've been writing in English for far longer than C++, and I still create typos in English every once in a while. The idea that a smart C++ programmer would never accidentally spell a common idiom wrong is absurd.

    A smart C++ programmer is one who recognizes common mistakes (*especially* those which might be made by another programmer on his team who isn't as savvy) and adjusts his coding style to make such mistakes less likely, especially when it costs you nothing (it doesn't even increase the character count).

    --
    It's always a long day... 86400 doesn't fit into a short.
  65. Re:C++ has bigger memory issues by LarsWestergren · · Score: 1

    The only way to read the filechannel is a bytebuffer. Has anyone ever used them? I had to once and it sucked....

    I've used them. What did you not like about them?

    FileReader (or BufferedInputStream) are still awkward because tehy use byte and string arrays. Those really are hard to work with w/o doing conversions in java, where in C the char arrays are usfule w/o conversion.

    Ok, there is also RandomAccessFile which gives you methods for reading all primitives, byte arrays, UTF-8 Strings, whole lines....

    Used for instance here to do high performance Linux Cluster Monitoring. Doing a C implementation saved them a whopping one second per day of processor time.

    --

    Being bitter is drinking poison and hoping someone else will die

  66. Unix Domain Sockets? by Eravnrekaree · · Score: 1

    Unix Domain Sockets use shared memory to transfer data between applications. How does this compare to other shared memory methods in performance?

    1. Re:Unix Domain Sockets? by TheRaven64 · · Score: 1
      Most forms of local IPC use shared memory. Pipes, for example, use a short shared buffer into which one process writes, and another reads. If you use shared memory directly you eliminate two copy operations (one into the shared memory and one out) and possibly four context switches to/from kernel space (two for the sender and two for the receiver. It may, therefore, be faster.

      In practice, you probably won't get much benefit. If you are not modifying the contents of the shared memory, then you might be better to store it in a file and mmap it read-only from both processes (this allows the VM system to just flush the pages when it is short of memory, since it knows they are the same as those on disk already). If you are modifying it then you will need to wrap accesses to it in some form of lock, which may well add more overhead. Remember: copying small amounts of data is actually very cheap - cache to cache copies are among the fastest things you can do on a modern CPU.

      Another disadvantage of using shared memory is that you end up with aliasing - there are multiple references to the same object. This is sometimes unavoidable, but it is good to keep it to a minimum because it makes it much harder to reason about your code, and harder to debug.

      The most important disadvantage of direct use of shared memory, however, is that it makes your code a lot harder to port to a multicomputer. If your code is performance-critical enough that you would think about using shared memory, then it would probably be better run on a cluster. If you stick to a message passing model then you will find that your code is a lot more scalable. Abstract the IPC away in your implementation, and you can replace it with sockets or MPI (or whatever) when you need to.

      --
      I am TheRaven on Soylent News
  67. And? by ratboy666 · · Score: 3, Interesting

    Ok, I get it... it's an attempt to exploit shared memory in C++.

    And why is this news? Is it so difficult that nobody has done it? No, that can't be -- the shm stuff can be wrapped. This is so important that it rates a "design pattern"? Not it either -- the one illustrated isn't the best solution.

    So, just what is this article? Methinks fluff. Sort of in line with "How to implement co-routines with setjmp/longjmp" thing. Or, "Restructuring data to assist processor cache residency". And "How to remove locks from performance critical MP code".

    Except not as interesting or useful.

    Ratboy.

    --
    Just another "Cubible(sic) Joe" 2 17 3061
    1. Re:And? by Ben+Hutchings · · Score: 1

      It's worse than that. The code has glaring errors in it. It's just awful.

    2. Re:And? by ObsessiveMathsFreak · · Score: 1

      And why is this news? Is it so difficult that nobody has done it?

      People have done it. Half the reason they do it is because it is difficult and they get some kind of buzz from writing ugly, ugly hacks. I've never had the pleasure of meeting such an abomination of code in person, but if I did, I'd send it screaming to /dev/null.

      Except not as interesting or useful.

      Amen.

      Shared memory. What kind of idiot uses shared memory. Never mind the bugs and hacks. Just think of the communication overhead. What the hell are all you're CPU's doing talking with one another so much?! They're supposed to be running in parallel!

      Cut down on inter thread communication and use flatfiles, or named pipes if you're feeling especially superior.

      Shared memory. I'll share your memory you... scallywag!

      --
      May the Maths Be with you!
  68. Re:10 fold speed improvement- It's a flawless idea by Anonymous Coward · · Score: 0

    It can be tweaked to avlod busy waiting, obviosly. The code is a clear skeleton example. you would sleep, or suspend, or force context switch in the busy wait section after a certain amount of microseconds elapses. Also on can assume that the mutex itself is controlling a single shared VARIABLE or RECORD, and that the entire time waiting is nanoseconds at maximum in best case. THINK!!! This is a special tool, and can be made slower or bloated if needed, but not necessarily nonoptimal even in skeleton design!

    secondly :
    IT IS SCALABLE for a few tasks. i would not setup more than 20 of them, but many situations only need 3 or less tasks sharing one message bin. Yes of course you need the make X copies of specially crafted code depending on the design.

    Remember the point, We are talking over 10 times faster... that is all that counts, and that is still an inarguable fact comapred to the linux example code in the article.

    finally : as for how to pass the turn, instead of two opcodes to exit, you would add an increment, and the special code for the final participant would merely set back to 0

    FAST FAST FAST!!!! potentially over 500 million transactions per second protecting a tiny data structure on normal machines

    You've just gotta love Dekkers

  69. Re:C++ has bigger memory issues by Pastis · · Score: 1

    If you mean a pure OO language like Java, in which everything is an object except for primitives stated elsewhere, this is contradictory. Try Python or Ruby. it takes ten classes and wrappers just to read a file ten classes might be too much. Sun went for flexibility and tried to give control to the programmer, exposing the API internals. Java was not designed for quick and dirty applications. But noone prevents you to write your class that eases simple file reading. E.g. package util class MyFileReader { String readFile(File) {... } } In fact you find libraries that do that on the Net. Look at Jakarta commons. Sun's API are a little bit raw in some areas. I think it was by intent. It's a trade of. They expected people to build on top of their fundations. They're not Microsoft. I tell you what though, C++ is still around after all this time. So it COBOL. Languages don't go away. the god awful sytax Stroustrup left them with C++ was *designed* to be like that. It had some requirements with regard to syntax being close to C. It requires discipline to use. But it's not that bad a language. Otherwise it wouldn't have been used as it has. There is still no successor to C++. successor for what goal? A language is a tool and not a universal solution. Java is better for some tasks, so is Ruby, Python, C#.... C++ has its uses, but today, although I like it, I find myself much more productive using other languages. Go and write a cross platform internationalized C++ web application with a thick client to communicate with. I wouldn't even know where to start.

  70. Re:C++ has bigger memory issues by LarsWestergren · · Score: 1

    The difference of course being that the C/C++ will still compile, and the Perl actually puts the error handler on the same line:

    I wouldn't call instantly ending a program with an error message "handling" a problem. If you have no demands on program reliability, you can always throw a RuntimeException("No such file: + fileName") in Java too.

    --

    Being bitter is drinking poison and hoping someone else will die

  71. High-level language? by The_Dixie_Flatline · · Score: 0

    I've seen this before, but why is C/C++ marked as a high-level language (as in the summary)? C/C++ are LOW-level languages - closer to the hardware, while languages like Visual Basic are HIGH-level languages since they abstract hardware-related tasks like memory management away.

    --
    -- Proof by analogy is fraud.
    1. Re:High-level language? by psykocrime · · Score: 2, Informative

      I've seen this before, but why is C/C++ marked as a high-level language (as in the summary)? C/C++ are LOW-level languages

      I've never heard that before... everyone I know, and all the literature I've read that described programming languages, considers assembler as "low level" and anything at a higher level of abstraction as "high level." With the exception of a few folks who try to describe C as a "mid level language" or as "high level assembler."

      Calling C++ a "low level language" is absolutely a mistake anyway. It's really a mixed-paradigm language, which includes "low-level" abstractions and some very "high-level" ones. Just because you have the option of dropping down to a low-level close to the hardware doesn't mean you have to.

      --
      // TODO: Insert Cool Sig
    2. Re:High-level language? by Anonymous Coward · · Score: 0

      So if it's not _as_ high level as VB, it can't be high level at all?

      If you're not with us, you're with the terrorists!

  72. Re:C++ has bigger memory issues by qray · · Score: 1

    That breaks down sometimes, sure, but that's when your "backup mechanism" would come into place

    Either way, you should always have options. At least I can bolt on GC (bhoem) to C++, I can't choose anything but GC in Java or C#. From what I've heard GC will probably be offered in the next standard of C++.

    Most of the leaks people talk about are from old style C++. With smart pointer classes and such I rarely if ever have to explicity remember to add a "delete". And I rarely have memory leaks. Where that breaks down is in cyclic references. And I only occasionaly encounter situations where I have such cyclic reference and where ownership isn't clear cut. But for those cases, I really wished for a GC mechanism in the language.

    But I think it boils down to giving the engineer a selection of tools not limiting his selection. --
    Q

  73. Re:Microsoft code? by WraithRealm · · Score: 1

    I just realized, I'm a C# dev, so that may not actually be how it is in C++. Sorry for the confusion.

    --
    I aim to misbehave.
  74. Re:C++ has bigger memory issues by LDoggg_ · · Score: 1

    That everything is an object in Java except for the primitive types are such a cop out by Sun.

    Is this really such a problem?
    The standard wrapper classes(Integer, Double, etc.) have been around since 1.0 and are part of java.lang so they don't even have to be explicitly included in the code.
    I've never been confused as to when I needed an object over the effeciency of a primitive data type.

    And as of 1.5, the collections classes automatically box and unbox primitives into their corresponding wrappers.

    --

    "If they have both, tell them we use Linux. And if they have that, tell them the computers are down." -Dave Chapelle
  75. Re:C++ has bigger memory issues by Viol8 · · Score: 2, Insightful

    "Easy programming languages"

    Excuse me? C may be many things , but easy isn't one of them.
    Ask any beginner. And as for the "security problems" in C , as
    you well know , C was designed as a replacement for assembler.
    It wouldn't have been much use if it didn't give you
    complete flexibility wrt memory access, even if that means
    breaking some of the rules that hand-held high level programmers
    use as a crutch because they're unable to code to the metal.

    "are uninterested in quality and very interested in meeting deadlines"

    If you have a mortgage and a family and your boss threatens you
    with the sack if you keep missing deadlines very few if any
    programmers will take the "moral" stand and get fired. And frankly,
    anyone who puts coding principles above their family is scum IMO.

  76. Java has the answer, as usual... by barbazoo · · Score: 0, Troll
    public class Montior {

    public synchronized foo() { <access shared data> }

    }

    or

    synchronized (theMonitor) { <do stuff with shared data> }
  77. Re:C++ has bigger memory issues by Viol8 · · Score: 1

    "In Smalltalk, everything is an object even the primitive classes!"

    And thats why it was so goddamn slow on old 16 bit machines
    and no one used it.

  78. Re:C++ has bigger memory issues by Viol8 · · Score: 2, Insightful

    Actually I tend to find the opposite. With C everything has to be explicit. ie you want a function called, you have to call it at
    that point in the code. WIth C++ you can use opertor overloading,
    polymorphism, hidden convertions , template specialisation and lots of other stuff which makes the actual code more implicit than C and hides whats actually going on away more. Sure , if you spend some time looking at the code you'll figure it out , but C++ doesn't IMO lend itself to skim reading as much as C does.

  79. Re:C++ has bigger memory issues by Viol8 · · Score: 1

    "Contract programing is in the works,"

    Great , more unwanted flavour-of-the-month-in-the-academic-ivory-
    towers cruft in an already bloated language. How many more ways can
    people think up to make a CPU run instructions over data?

  80. There are better ways by photon317 · · Score: 4, Informative


    A lot of shared memory synchronization and/or caching problems can be solved on Linux through the effective use of a few simple things:

    1) shm_open (if seperately-started processes which need to coordinate in shared memory), or mmap(MAP_SHARED|MAP_ANONYMOUS) for a process which will fork children which need to communicate/share between themselves and the parent.

    2) Use 's "atomic_t" integer type within that shared memory array (atomic_t* my_shm_array = mmap(....)). The atomic_t type has several functions defined in that header for atomic read, write, increment, etc for the linux hardware platform at hand. On most sane (cache-coherent) SMP architectures, reading and writing are already atomic operations, so this basically devolves to just setting and getting integers like normal (with a little bit of syntactic sugar (struct { volatile int val }) to make sure the C compiler doesn't optimize things away that it shouldn't. And you can implement a whole lot of sane algorithms using nothing but shared memory integer reads and writes with no locking or special atomic increment ops.

    3) If you need more advanced or complex locking on the shared memory for synchronization, use Linux's "futex"'s. They're in the man pages, and they're really fast.

    --
    11*43+456^2
    1. Re:There are better ways by bogolisk · · Score: 2, Interesting

      1) shm_open(2) is already mentioned in the 2nd post.

      2) dont u know that NPTL is already doing this for u? On fast-path, NPTL's posix mutex just do atomic operations and avoid doing syscall. Stick to the standard API and let the platform guys (libc, kernel, ...) do the optimization. They're smarter than u.

      3) u dont want to do this, seriously! if futex is that consummable by the public, then why did the glibc guy write a looooooong paper describing howto use futex.

      --
      Bogus
    2. Re:There are better ways by Anonymous Coward · · Score: 1, Funny

      It's remarkable how one can write an insightful post and yet lose all credibility by choosing not to bother typing the entire word "you". Well done.

  81. Re:C++ has bigger memory issues by Richard+W.M.+Jones · · Score: 1
    Proper freeing of memory and sane buffer management goes a long way to creating good, secure code.

    Yes, but in every instance I have seen C++ programmers end up implementing reference counting (by hand) in order to make these problems tractable. Unfortunately reference counting is a horribly inefficient solution compared to a decent garbage collector. Often C++ programmers don't understand why reference counting is a bad idea, assuming that just because its large cost is spread over many operations it must be "obviously" better than those "stop-the-world" (bad) garbage collectors you find in Emacs and Java 1.0.

    Rich.

  82. Re:C++ has bigger memory issues by moro_666 · · Score: 1

    nobody forces you to use these new bytebuffers, they are mostly intended for async i/o, which most applications certainly dont need, their misuse makes things a lot worse usually :D

    last time i checked, new FileInputStream("foo.txt") returned a sane 1 class wrapping around InputStream, which is actually as close to the ideal OOP model as it gets.

    java's big advantage over old generation programming languages is that char != byte, which makes all kind of utf8 and utf16 handling transparent and very comfortable. for unexperienced new players, this ofcourse gives a lot of painful lessons too. the other big advantage is that all java libraries (unless written by serious "einsteins") can be mixed with eachother without much trouble, whereas very many languages have brilliant api's for some things that don't work with some other brilliant libraries at all (ithreads and lwp|tcltk for perl as an example).

    c++'s biggest power imho is to directly include pure C code without any special hacks, this allows you to use the very core libraries of your operating system and gives it speed and comfort using the standard stuff, this is something that most languages miss big time.

    comparing the stuff is pointless as stated many many times before by many many people besides me. use the right tool for the right job. c++ is the right tool for many things right now, use it where you have to use it (unless you have something that really is better, which is not mostly the case for low level stuff)

    --

    I'd tell you the chances of this story being a dupe, but you wouldn't like it.
  83. Java-trolls are clueless, as usual... by bogolisk · · Score: 2, Insightful

    The article is about shared-mem and synchronization accross process boundary! In Java that would mean: object that are shared between VMs; methods are are serialized across VM boundary.

    --
    Bogus
    1. Re:Java-trolls are clueless, as usual... by barbazoo · · Score: 1
      java.nio.MappedByteBuffer
      java.nio.channels.FileC hannel
      java.nio.channels.FileChannel.MapMode
      Possiblilty to lock entire memory mapped file, or portions thereof.
    2. Re:Java-trolls are clueless, as usual... by LarsWestergren · · Score: 1

      Writing to file is usually not considered a usable form of interprocess communication. What you are looking for is probably Sockets, or even better Channels.

      --

      Being bitter is drinking poison and hoping someone else will die

    3. Re:Java-trolls are clueless, as usual... by barbazoo · · Score: 1

      FileChannels can be memory mapped ya know...

    4. Re:Java-trolls are clueless, as usual... by bogolisk · · Score: 1

      first you claimed "synchronized" methods can sync across JVM boundary. once, proven to be wrong, you came up with java.nio. Now, please enlight us how java.nio can do inter-JVMs mutual exclusion?

      And how is it better than pthread mutex (with NPTL), which is very fast (on non-contention path, it's only dozen instructions no syscall) and provides inter-PROCESS mutual-exclusion.

      We not talking about thread here, the article is abound inter-PROCESS communication.

      --
      Bogus
  84. yeah, fast, and 10-fold chance of odd failures by Krischi · · Score: 5, Informative

    Yeah, this algorithm is fast. Too bad that it does not work. This kind of design is a common mistake by people who do not understand the intricacies of multithreaded programming. In short, it fails miserably when the CPUs are allowed to reorder loads and stores, a.k.a. pretty much any modern CPU. You need a memory barrier between setting and testing of a shared variable.

    Google for Dekker's algorithm and memory barrier - you will find better explanations of the problem there than I could type up in my limited time here right now.

    1. Re:yeah, fast, and 10-fold chance of odd failures by Anonymous Coward · · Score: 0

      You are incorrect! The code is sound.

      I (the dekker submitter) design and write firmware for for high end PCI-X I/O controllers and I can assure you that the statement in the original posty that CLEARLY stated : "as long as shared memory is cache coherent" is all you need for safety with a design that uses two or more state flags as a gate (as this design builds upon).

      the flag bytes are stored in their own cachelines. if you claim that the safety opcodes "eieio() sync(), or isync()" for powerpc are needed you are incorrect. if the cacheline is in non cache memory, or is otherwise cache coherent, then the algorithm does not die from your so called "memory barrior", even if flipped order from what is assumed, and if you are truly paranoid a third state flag could be added.

      Ive now posted 5 rebuttals and am giving up trying to teach anyone anything... even when the code is as simple as i can make it... then people like you try to redefine the meaning of cacheline coherency.

      sheesh

    2. Re:yeah, fast, and 10-fold chance of odd failures by Furry+Ice · · Score: 1

      The point is that your algorithm is only correct for particular architectures. It works wonders on the Von Neumann arch and on modern SMP machines which maintain full cache coherency. It's equally important to note that such machines are going to become less common with time as greater degrees of concurrency become the only remaining path to higher performance. It's vitally important that programmers begin to understand these issues, because they are not at all obvious and can lead to very difficult bugs to understand and reproduce. I really think insufficiently synchronized code will slow the adoption of highly parallel hardware, making software the ultimate bottleneck for Moore's law.

      Or maybe people will finally give up on threads. :-)

    3. Re:yeah, fast, and 10-fold chance of odd failures by LO0G · · Score: 1

      It doesn't even work on current Intel and AMD processors. But as long as your code is running on a uniprocessor platform, you'll never see the problem (because the write-ordering issues are hidden on a single processor).

      This code may very well work in the narrow scenario in which you're using it, but it's NOT a general purpose solution to the problem.

  85. Re:10 fold speed improvement - The Phd was idiot by Anonymous Coward · · Score: 0

    WRONG!

    The Phd had no argument based on efficiency... he claimed it was physically impossible to avoid special hardware support (opcodes, mem control, etc).

    By the way it is 100% efficient if two cpus are sharing a single cacheline of memory as a small communications status record.

    imagine that reads or writes are bracketed around the cacheline with a call to the mutex.

    as soon as the byte or bytes are read or written, the mutex is dropped.

    idiots like you would take that pristine 100% optimal example of 500 million transactions per second and slow it down over 100 times slower probably!

    Do you ever think about what you are claiming! I am sorry i tried to teach anyone anything here.... its like talkign to retards. I have a respected Com Sci degree and it was not clearly discussed in the older days when i got my worth-crap diploma. instead people rely on HARDWARE based semaphores in machines. THERE IS NO NEED FOR THEM and that is the point.

  86. Concurrent Haskell by Hurricane78 · · Score: 1

    Well... i would rather recommend a good Haskell compiler as it's the successor of CML and a bit cleaner too. ;)

    Or use Ocaml if you like it lightning fast. (meaning: nearly beating raw C) Even in bytecode! (Beating java by far!)
    But it's not as clean as Haskell as it allows *shudder* side effects...

    --
    Any sufficiently advanced intelligence is indistinguishable from stupidity.
  87. Re:C++ has bigger memory issues by smcdow · · Score: 2, Interesting

    Like Java, right?

    Getting back to the original premise of the story, can you even do OS-level shared memory (SysV or POSIX) with Java? OS-level semaphores? Any meaningful kind of IPC? OS-level anything? I mean without godawful JNI nonsense.

    --
    In the course of every project, it will become necessary to shoot the scientists and begin production.
  88. Re:C++ has bigger memory issues by arkanes · · Score: 1
    Yes. Everything is an object in Python. Note that your statement wasn't true until recently (you couldn't inherit from most of the built-in types until 2.3), but it was still a pure OO language in that everything was an object.

    Of course, there is still some debate about what "Object oriented" means, and what it means to be "pure" OO. And by debate I mostly mean a combination of Usenet flaming and the academic equivilent of trash-talking. Suffice it to say that there is not a universally accepted definition of "object oriented", much less "pure object orientation".

  89. Re:Microsoft code? by Rakshasa+Taisab · · Score: 2, Insightful

    It has something to do with the direction in which you read the code, from the left to the right. In the former example, you'll have to push "EOF !=" on the mental stack before parsing the meaning of "(c = getc(stdin))".

    I like my manga right to left, my code left to right.

    --
    - These characters were randomly selected.
  90. Re:Microsoft code? by Anonymous Coward · · Score: 0

    In the same way that "elbadear" is less readable than "readable".

  91. Re:C++ has bigger memory issues by velco · · Score: 1

    Fine-grained GC is already in TR1 and should be available from major compilers pretty soon. It is interesting to note that GC is being done in the standard library, unlike C# which does it in the core language. Some would propably claim this means C++ doesn't have "true" GC support, rather than realizing it is just a different approach to the problem.

        TR1 does NOT provide "Fine-grained GC". It provides std::tr1:shared_ptr, which is capable of solving some of the automatic memory management[1] requirements of SOME programs and completely fails (as in "unbound memory consumption") in others. While indeed being a different approach to memory management, it is nonetheless not a "true" solution by virtue of being non-transparent (i.e. not fully "automatic"), incomplet and inkorrect.

        The above, of course, assumes the said smart pointer is impemented with reference counting, although the standard does not mandate particular implementation. However, any other implementation, which is both transparent, complete and correct would necessitate a C++ runtime, which would make the smart pointer, well, pointless in the first place.

    [1] the proper name of the so called "garbage collection"

  92. Not much experience on this but... by hdante · · Score: 2, Informative

    The mutex doesn't seem to be shared between processes. This would make the code incorrect. Can anyone confirm this ?

  93. Perl and Die by Zan+Lynx · · Score: 1

    The neat thing about "die" in Perl is that it instantly converts into an exception just by wrapping the function call inside an "eval { }"

    1. Re:Perl and Die by LarsWestergren · · Score: 1

      The neat thing about "die" in Perl is that it instantly converts into an exception just by wrapping the function call inside an "eval { }"

      Ahh. Didn't know that. You are right, that is pretty nifty. Still prefer the Java way though. :-)

      --

      Being bitter is drinking poison and hoping someone else will die

  94. Re:C++ has bigger memory issues by Rakshasa+Taisab · · Score: 1

    Balanced like tr1::shared_ptr and friends in TR1? The lack of standardized GC support in C++ is no longer a valid argument. Now all that is needed is for them to be implemented in the major compilers.

    Though it still doesn't solve the problem of bad coders.

    --
    - These characters were randomly selected.
  95. Re:Microsoft code? by Curien · · Score: 1

    (Ignoring the typo)

    More like still perfectly understandable this sentence is.

    --
    It's always a long day... 86400 doesn't fit into a short.
  96. Re:Microsoft code? by Curien · · Score: 1

    C and C++ already have precedent for reading things backwards:
        int const *const foo; /* foo is an immutable pointer to an immutable integer */

    --
    It's always a long day... 86400 doesn't fit into a short.
  97. not really usefull by vtoroman · · Score: 2, Informative

    The code shown is using pthread mutex for sync-ing. The mutex works only for synchronization of threads, not processes so the code is useless (even dangerous) for inter process communication (IPC). In the case of threads another question is just screaming for an answer:
          Why would someone use a shared memory block for threads which are all running in the same memory space anyway?

    We come to the conclusion that the code is quite useless for inter-thread communication too. All in all - useless.

    1. Re:not really usefull by Ben+Hutchings · · Score: 1

      Mutexes can be used between processes (though the old LinuxThreads didn't support this). It helps if they're stored in shared memory as well, rather than static storage, though...

    2. Re:not really usefull by vtoroman · · Score: 1

      I am sorry but that is not true. I have compiled some test code with gcc 3.3.6 and started two instances of it and the output showed that the mutex did not block between processes, at least not with the options from the article (both processes are in the critical section at the same time). Where did you get the information that pthread mutexes synchronise between processes? Man pages for pthread_mutex_init, pthread_mutex_lock, pthread_mutex_trylock etc do not mention it at all.

    3. Re:not really usefull by vtoroman · · Score: 2, Informative

      The only way to make mutexes interprocess is to enable pthread_mutexattr_setpshared attribute. This hasn't been done in the article's code so the mutex which is used there hase an inter-thread scope, not an inter-process scope.

    4. Re:not really usefull by Ben+Hutchings · · Score: 1

      This doesn't actually contradict what I said...

    5. Re:not really usefull by vtoroman · · Score: 1

      I know, my bad :) should read more carefully

  98. Re:10 fold speed improvement - The Phd was idiot by LO0G · · Score: 2, Informative

    The PhD is STILL right.

    That code makes a huge fundimental assumption, that write order is preserved. In other words, if you do:

    Write to location 3 on processor 1 (take the lock)
    Read from location 30 on processor 1 (do stuff with the lock held)
    Read from location 3 on processor 2 (check the lock)

    that the reads and writes will appear in order. On ALL modern processors, this assumption is not true, it's possible for the write to location 3 to occur AFTER the read from location 3 on processor 2. It works great on single processor machines, but fails on MP machines.

    In order to make the code work, you need to put a memoy write barrier after the write to location 3, this will force the write to be flushed from the cache.

  99. Re:C++ has bigger memory issues by miu · · Score: 1
    Ofcourse this is usually a programmer problem more than anything

    I'd say it is entirely a programmer problem. C++ programmers who write C programs (for whatever reason) tend to organize things just as they would a C++ program.

    --

    [Set Cain on fire and steal his lute.]
  100. textbook algorithm by Anonymous Coward · · Score: 0

    This is of course a textbook algorithm. Every textbook will also tell you that it has a fatal flaw (except from the busy waiting, which the textbook we were using (Ben-Ari) wasn't even interested in): if a process that holds the turn crashes or terminates, the whole system deadlocks. That makes the whole thing, unfortunately, rather useless.

    1. Re:textbook algorithm by Anonymous Coward · · Score: 0

      oops, I looked better and that only holds if the process crashes while it holds the mutex - and it is a common assumption that that doesn't happen. I was fooled by the looping on the turn without looking a bit further.

  101. Re:C++ has bigger memory issues by Anonymous Coward · · Score: 0

    technically, you don't "know" it's not changed. the function could be using const_cast<> and changing it that way. but then of course that function's violating it's contract :)

    --vat

  102. Re:10 fold speed improvement - Dekkers mutex ! fas by fitten · · Score: 1

    It would still result in massive CPU usage, compounded with potentially lots of MOESI traffic on the caches. These are some of the reasons why it isn't used anymore. If it were the end-all, be-all as you claim then why wouldn't this be used everywhere? I mean, it's not like the algorithm hasn't been around since 1965 (as you also stated).

    Basically, the reason is this: Polling, especially in a single CPU environment, is a BadThing(tm) if you want your machine to handle load well. If you have no load and have nothing else useful for your CPUs to be doing, then polling is about as good as anything else. Considering that all modern OSs are pre-emptive and are doing lots of things during any given second, few would meet that criteria.

  103. Re:C++ has bigger memory issues by fitten · · Score: 1

    Compounded by the fact that many "by hand" implementations of reference counting is defective. I've seen many broken hand-tooled reference counting schemes.

  104. Re:C++ has bigger memory issues by Anonymous Coward · · Score: 0

    java.nio.* and java.util.concurrent.* provide relatively high level API that is implemented with the most efficient OS calls possible (actually it depends on the quality of the implementation. . .).

    It may not be as general as straight Sys V IPC or what have you, but it will probably cover the majority of cases.

  105. Re:Microsoft code? by Malc · · Score: 1

    It's still good practice. One day you might working with an older compiler for some reason (perhaps on a maintenance project) that doesn't warn. Perhaps you'll be working with another language that isn't so helpful: for instance I've been working on some ECMA Script applications recently and my habits like this from the old days of C++ help me deliver more reliable code.

  106. Re:C++ has bigger memory issues by nagora · · Score: 1
    C/C++ doesn't prevent you from coding secure, leak-free programs.

    That is what I said, yes.

    TWW

    --
    "Encyclopedia" is to "Wikipedia" what "Library" is to "Some people at a bus stop"
  107. Re:C++ has bigger memory issues by nagora · · Score: 1
    Like Java, right?

    Not really, no.

    Getting back to the original premise of the story, can you even do OS-level shared memory (SysV or POSIX) with Java?

    I dunno. Never tried. I would imagine not, given the sandboxing that goes on.

    TWW

    --
    "Encyclopedia" is to "Wikipedia" what "Library" is to "Some people at a bus stop"
  108. Cache choherency is NOT sufficient by Krischi · · Score: 2, Interesting

    You don't get it about out-of-order writes, do you? Simple scenario, according to your algorithm:

    CPU AA:

    resource = produce_something();
    turn = BB;
    flags[AA] = FREE;

    CPU BB:

    flags[BB] = BUSY; /* CPU AA clears its BUSY flag at this point in time, so, the while (flags[AA] == BUSY) terminates immediately */
    consume(resource);

    The problem is that AA is free to reorder its writes. So, the actual order could be:

    flags[AA] = FREE; /* from AA */
    flags[BB] = BUSY; /* from BB */
    consume(resource); /* BB uses the resource */
    resource = result of produce_something() call /* writeback from AA is too late */

    Oops. BB accesses the resource before AA writes back the current state. Cache coherency does not solve this problem - the problem is that the write to the resource is still pending. That is what the memory barrier is there for.

    Argue with facts, don't hide behind oh-so-impressive credentials.

    1. Re:Cache choherency is NOT sufficient by Furry+Ice · · Score: 2, Insightful

      This is why closed-source drivers are a bad idea. There are a lot of coders out there who are so impressed with their own credentials that they just don't take the time to read and understand why their clever little hacks don't work. Then, when they try their driver on an architecture where their assumptions don't hold, they give up. The product is probably old and they make a business decision that it's not worth updating the driver for the new architecture.

    2. Re:Cache choherency is NOT sufficient by Anonymous Coward · · Score: 0
      The problem is that AA is free to reorder its writes.

      Not only that, but the compiler can reorder memory accesses during optimization. This paper goes into details about why multithreading can not be implemented correctly without special compiler support. (And though the paper's abstract does not make it clear, pthreads does have the support necessary for correctness.)

  109. Re:C++ has bigger memory issues by 2short · · Score: 1

    But the point is really that the compiler "knows" it is not changed, which lets it do various optimizations it could not otherwise. Which might well cause problems if you use const_cast<>

  110. If anybody put that in my code I'd smack 'em. by MS-06FZ · · Score: 1

    Personally I think actions have no business whatsoever inside the condition clause of an "if", "while", etc. "x = foo()" can easily go on another line. And if someone is sick enough to really want a side-effect inside of a boolean clause, they should use parens to make the order of operations easy to read.

    As for the more general issue of "backwards comparisons"... The big thing I guess is that it helps people remember not to type "if (x = 3)" or whatever... not that that'll help them if both values being compared are variables.

    --
    ---GEC
    I'm but the humble pupil, seeking to snatch the scratchbuilt pebble from the master's fully articulated hand
    1. Re:If anybody put that in my code I'd smack 'em. by Curien · · Score: 1

      The issue isn't whether or not to use parens, but whether one should code defensively to avoid forgetting them. Parens are necessary either way:
          test(CONSTANT == (var = func()))
      versus
          test((var = func()) == CONSTANT)

      The the detractors claim that it reads unnaturally. The proponents note that if you accidentally forget the parens
          test(CONSTANT == var = func())
      is a syntax error, whereas
          test(var = func() == CONSTANT)
      is a logic error.

      --
      It's always a long day... 86400 doesn't fit into a short.
  111. Re:C++ has bigger memory issues by Jamu · · Score: 1

    C/C++ doesn't prevent you from coding secure, leak-free programs.

    That is exactly what I said.

    --
    Who ordered that?
  112. Re:Microsoft code? by Malc · · Score: 1

    I'd say anybody doing either has poorly-written code. Stop trying to do so much on one line. With our massive displays these days code doesn't become less readable when spreading things out over more line because we can see so many lines anyway. Spacing the code out more vertically makes it easier to read and less error-prone too.

    c = getc(stdin);
    if (EOF != c)
    { ...

  113. Objective-C? by ashpool7 · · Score: 1

    Does that count as a replacement?

    1. Re:Objective-C? by swillden · · Score: 1

      I prefer Objective-C++.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    2. Re:Objective-C? by ashpool7 · · Score: 1

      That's just a bridge, not a language.

    3. Re:Objective-C? by swillden · · Score: 1

      Whatever you want to call it, you can write programs with it, applying both the static typing of C++ where that makes sense and the extreme run-time flexibility of Objective-C where that makes sense. The learning curve is rather steep, but it's very powerful once you figure out where to use what.

      --
      Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
    4. Re:Objective-C? by Anonymous Coward · · Score: 0

      I see it as "two ugly compiler hacks in one."

  114. Re:C++ has bigger memory issues by nagora · · Score: 1
    Excuse me? C may be many things , but easy isn't one of them. Ask any beginner.

    Compared to most languages, C is very easy to pick up the basics of. That's why C-like languages rule the programming world. There are some tricky parts but the basic structure of a C program is something even beginners grasp very quickly, and I've tutored quite a few.

    If you have a mortgage and a family and your boss threatens you with the sack if you keep missing deadlines very few if any programmers will take the "moral" stand and get fired.

    Which is why so much code stinks. Just because there is a good reason for it stinking doesn't mean it suddenly becomes good code or stops crashing. There's no "Blue screen of morally acceptable quality compromise" that pops up and then allows the program to continue on as if nothing had happened.

    TWW

    --
    "Encyclopedia" is to "Wikipedia" what "Library" is to "Some people at a bus stop"
  115. Preying on the non-comp SCI mods, I see. by Inoshiro · · Score: 4, Insightful

    "How many people know about this? Nobody! I never read about it anywhere. I invented it myself years ago, .."

    Turn to page 55 of your OS design and implementation by Tanenbaum. See where he says, "For a discussion of Dekker's algorithm, see Dijkstra (1965)."? How do you get through a proper comp sci honours degree to the point where you can take a masters and then a PhD without reading Dijkstra?

    How about you crack open that copy of Operating Systems (4th ed) by William Stallings, which has a discussion of concurrency and Dekker's on pages 208-213? How can you get past a 2nd/3rd-year introductory operating systems class without having gone over this topic?

    You are a troll. A troll preying on the fact that most of the moderators here have no idea about computer science, and have not taken a wiff of a real operatings systems class.

    For the record, Peterson's algorithm (published in 1981) is a much simpler solution to your problem. It's on page 56 of the Tanenbaum book, and also discussed in Stallings on page 213. There's a new 5th edition of the Stallings book, but the index will take you to the correct chapter/page in short order.

    --
    --
    Internet Explorer (n): Another bug -- that is, a feature that can't be turned off -- in Windows.
    1. Re:Preying on the non-comp SCI mods, I see. by ObsessiveMathsFreak · · Score: 1

      How do you get through a proper comp sci honours degree to the point where you can take a masters and then a PhD without reading Dijkstra?

      I don't know what kind of comp sci degree you got, but out there in the real world, it's a sorry story. Truckloads of graduates can do precious little but Java, some HTML 4.01, visual basic, ASP and most use Visual C++ if they look at C++ at all.

      Who am I kidding. Forget the java part. They're learning C# now. Most don't know what an opcode even is, let alone how their code becomes a sequence of them. Three quarters have never even downloaded a Linux Live CD. A significant percentage believe that writing their code on one line will make it run faster. They write SQL statements that would make you openly weep. The commandline is regarded as a bug or error whenever it appears.

      But they can download torrents like nobodies business!!..... OK I lied. They're just using limewire. I blame the lecturers.

      --
      May the Maths Be with you!
    2. Re:Preying on the non-comp SCI mods, I see. by MmmmAqua · · Score: 1

      You are a troll. A troll preying on the fact that most of the moderators here have no idea about computer science, and have not taken a wiff of a real operatings systems class.

      I think you are generalizing a bit too much here. I've taken years of computer science courses, and I still don't have a clue.

      --
      Arr! The laws of physics be a harsh mistress!
  116. Re:Microsoft code? by maxwell+demon · · Score: 1
    In that case, you can do
    while (true) // while(1) for C
    {
      x = foo();
    if (x == -1) break;
    ...
    }
    I consider this cleaner than the combined assignment/compare in the while condition. YMMV. Note that if you ever need to replace the simple call to foo() by something more complex, you'll have to switch to this form anyway, or it will become unreadable quite quickly.

    And yes, it's still single entry/single exit - it's just that the exit is syntactically in the middle of the loop body.
    --
    The Tao of math: The numbers you can count are not the real numbers.
  117. Re:C++ has bigger memory issues by nagora · · Score: 1
    You say that as if C++ isn't in use by the vast majority of software houses on the planet, and rather successfully for that matter.

    I would dispute the second part: has code quality improved in these houses, or anywhere in the last 15 years for that matter? Has the number of late, canceled, or over-budget projects decreased?

    I simply don't believe that the currently popular languages have anything substantial to offer when it comes to solving the big problems of computing. C++ is a hack, but it is a very popular hack which brought the concepts of OOP to a lot of people. Just enough of those concepts, in fact, to stop most of them asking for more.

    Not having a GC, retaining the idea of keywords and primatives, the dire template system. These are all huge flaws in the OO model of C++. Some have been patched over the years and some are being patched as we speak, but I have little faith left in the language as anything other than a useful deadend, like COBOL was in its final years.

    TWW

    --
    "Encyclopedia" is to "Wikipedia" what "Library" is to "Some people at a bus stop"
  118. Re:C++ has bigger memory issues by swillden · · Score: 1

    WIth C++ you can use opertor overloading, polymorphism, hidden convertions , template specialisation and lots of other stuff which makes the actual code more implicit than C and hides whats actually going on away more.

    C++ code tends to more clearly express the programmer's intent. C code tends to more clearly express the implementation details. When reading C, you start by looking at what the code does, then work upward to figure out what the programmer intended to accomplish. When reading C++, you start by looking at what the programmer wanted you to see, then dig down to find out exactly how it was done.

    That's all a gross generalization, of course. C can be written so that it's very clear, C++ can be written so that it exposes the details, and both can be horribly obfuscated.

    Assuming both were written by good programmers, I'd rather read C++ than C. It takes less effort to get the gist of what's going on, and I can always dig into the details if I need to.

    --
    Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
  119. Re:C++ has bigger memory issues by Viol8 · · Score: 1

    "There are some tricky parts but the basic structure of a C program is something even beginners grasp very quickly, and I've tutored quite a few."

    Structure is hardly the same as syntax , and C structure is
    simply procedural anyway. Explaining pointers , dereferrencing,
    stacks, heaps, bitfields ,unions, stdio buffering, pre processor
    tricks and all the other stuff you need to become a *good* C
    programmer to beginners is not easy. Any idiot can do printf("hello world\n");, but take that idiot and give him the linux
    kernel code to look at and then tell him C is easy.

  120. Re:Microsoft code? by maxwell+demon · · Score: 1

    Actually, foo is an immutable pointer to a possibly immutable integer (it can also point to a mutable integer).

    Now, you hopefully don't think C++ declaration syntax (which is this way due to C backwards compatibility) is something you should imitate. Indeed, Bjarne Stroustrup himself said: "I consider the C declarator syntax an experiment that failed." (in the answer to question 3, paragraph 4)

    --
    The Tao of math: The numbers you can count are not the real numbers.
  121. Re:10 fold speed improvement - The Phd was idiot by Gilk180 · · Score: 1

    There is another assumption that may not hold (but usually does).

    The code assumes that a writes are atomic. This will almost always hold for 8 processes and usually form 32, but if the flags array is larger than a word, atomic writes go out the window.

  122. I don't see how this can work by pclminion · · Score: 1
    The authors use SysV shared memory, which can be shared between processes. But pthreads mutexes are limited to the threads of a single process only. I might be missing something, but it appears this design is fatally flawed, because threads from different processes sharing the shared-memory object cannot properly synchronize their access.

    However, given that these people are IBM engineers, I'll give them the benefit of the doubt -- can somebody explain what I'm missing here?

    1. Re:I don't see how this can work by bheading · · Score: 1

      AFAIR, that's incorrect. It's possible to put POSIX mutexes (created with a certain SHARED flag) into shared memory segments and share them between processes that way. W. Richard Stevens uses at least one example of this in his book on IPC. I haven't RTFA to check whether they are doing this though.

    2. Re:I don't see how this can work by pclminion · · Score: 1
      It's possible to put POSIX mutexes (created with a certain SHARED flag) into shared memory segments and share them between processes that way. W. Richard Stevens uses at least one example of this in his book on IPC. I haven't RTFA to check whether they are doing this though.

      They aren't. I know about this too, and they don't seem to be using it.

  123. Ah, but that's easy. by Estanislao+Mart�nez · · Score: 1

    I think it's perfectly fine to subscribe to the OP's take on this: a language is purely object oriented if all instances of all types are objects, except for the ones that aren't.

  124. Too bad all programmers are sloppy. by Estanislao+Mart�nez · · Score: 2, Insightful
    C/C++ doesn't prevent you from coding secure, leak-free programs. All it does is shift the responsibility for security and memory management from the language to the programmer. If you're a sloppy programmer then, yes, you need a better language than C/C++.

    Experience demonstrates that, by and large, even very good programmers commit a sizeable number of these errors. Not to mention that ensuring proper security and memory management takes time; and time is money.

    1. Re:Too bad all programmers are sloppy. by Anonymous Coward · · Score: 0

      You do not need to be very good to write code without these types of errors. You do need to recognize your own limitations and learn how to use the computer(or other resources) to compensate for them. One way to do this is to use a programming language that does not allow these errors. There are other techniques that are not as blunt that can be used in C and C++.

  125. Re:C++ has bigger memory issues by pyrrhonist · · Score: 1
    I'd say it is entirely a programmer problem. C++ programmers who write C programs (for whatever reason) tend to organize things just as they would a C++ program.

    Yeah, I just *hate* it when they define things in .hh files and put the implementation in .cc files.

    Those are the wrong file extensions, you rat bastards!

    --
    Show me on the doll where his noodly appendage touched you.
  126. Re:10 fold speed improvement - Dekkers mutex ! fas by AuMatar · · Score: 1

    Even with thread suspension, you need to wake up every so often to check the status of the flags. This leads to one of two outcomes.

    1)YOu use a long sleep timeout. This means your responsiveness is lower than using an OS semaphore, because you won't be woken immediately upon thread B finishing.

    2)You use a short sleep timeout. This means you will wake up and check the flag repeatedly. That measn incurring a contaxt switch into the program for every poll, which is far more costly than the switch to kernel mode.

    --
    I still have more fans than freaks. WTF is wrong with you people?
  127. Re:C++ has bigger memory issues by Stele · · Score: 1
    c++'s biggest power imho is to directly include pure C code without any special hacks, this allows you to use the very core libraries of your operating system and gives it speed and comfort using the standard stuff, this is something that most languages miss big time.


    C++'s biggest power by far is templates. For those of us writing graphics software, there is no better way to write one bit of code that operates on various pixel depths (8 bit channels, 16 bit channels, half float channels, full float channels), and let the compiler deal with the instantiations.

    Not many people mention this. When speed is paramount, and you need portable code, there is nothing better than C++.
  128. Re:C++ has bigger memory issues by nagora · · Score: 1
    Pointers are easy, stacks, heaps, io buffering, and bitfields are generic concepts which are not in any way specific to C.

    Any idiot can do printf("hello world\n");,

    The same idiot can easily grasp for loops, ++, --, subroutines and parameter passing, and a host of other syntax which allow the writing of useful programs in a very crude way, but they will work. And that's the problem. Once they get to this point the beginners think they are programmers and off they go to ply their trade. When they see C++ they think "Oh, I recognise this. There's some extra stuff about classes but that's just a way of organising your subroutines." and away they go. The end result is the sort of buggy code I see all the time, failed projects, cost overruns and unintelligable source.

    TWW

    --
    "Encyclopedia" is to "Wikipedia" what "Library" is to "Some people at a bus stop"
  129. Re:10 fold speed improvement - The Phd was idiot by AuMatar · · Score: 1

    You're hoping that the compiler decides to use a bitfield for booleans then. This does not have to be the case- a compiler is free to implement them as whatever they wish. I would expect chars to be a common choice. You'd need to rewrite the code as bitfields to ensure that.

    --
    I still have more fans than freaks. WTF is wrong with you people?
  130. Re:C++ has bigger memory issues by swillden · · Score: 1

    why are you passing it as a const reference instead of just a reference?

    Two reasons: Readability and const-correctness.

    When writing C++ it's a good idea to avoid passing parameters by non-const reference because doing so creates too much work for the next programmer who has to read the code. Since references don't exist in C, and many C++ programmers also write C, there's a natural tendency to assume that functions do not modify their parameters. This means there's a good chance that the next programmer who comes along will assume that your functions don't modify their parameters. If that assumption is invalid, he may break something. Even if the next programmer realizes that your function may modify its parameters, it's a problem because then he has to look at every function to find out if it does or not. If you're going to modify a parameter, pass a pointer, and try to take the address in the function call so that it's very visible.

    anobject.someMethod(&aParam);

    It's quite clear in the above that someMethod is probably going to modify aParam.

    So it's good style to avoid passing parameters by non-const reference. Passing by const reference is okay, because it doesn't change the semantics (excepting possible side effects by ctors/dtors or usages of const_cast<> by the function, but those are generally very bad style). Since it's semantically equivalent to passing by value, but more efficient, it's a good idea.

    Const-correctness is a very valuable tool in a C++ programmer's arsenal. The idea is that all objects, parameters and methods should be declared as const except where they actually need to change/be changed. This really helps to expose invalid assumptions about when things change and often enables the compiler to catch some programmer logic errors. It can also be a huge amount of work to make a program const-correct, and efforts to do so may run afoul of const-incorrect library APIs. IMO, const-correctness is sufficiently valuable to be worth doing, but probably not valuable enough to try retrofitting into an existing codebase, except perhaps as an exercise to build an understanding of the structure of the code (because you're gonna see almost all of it!).

    --
    Note to ACs: I usually delete AC replies without reading them. If you want to talk to me, log in.
  131. Re:10 fold speed improvement - Dekkers mutex ! fas by AuMatar · · Score: 1

    In addition to the problems of write ordering and busy looping, I have one more- your solution works only if you know how many threads will be accessing the resource beforehand. You have to choose an array size for the flags, and hope that you guessed a high enough number. That may be ok for some subset of problems, but not for a general solution.

    --
    I still have more fans than freaks. WTF is wrong with you people?
  132. Re:C++ has bigger memory issues by Anonymous Coward · · Score: 0

    What is your point, Java would be just as slow if not slower when implemented on such hardware with said limitations.

    There were probably other reasons as well, the whole image vs. source thing. Smalltalk was just too different.

  133. Re:0x1234... by hosecoat · · Score: 1

    0x1234... Amazing that's the same code I use on my luggage

  134. Re:C++ has bigger memory issues by kbw · · Score: 3, Interesting

    C++ is more than just an OO language. It provides direct support for the procedural paradigm too.

    STL, for example, is not an OO library. Yet it has proved to be immensly useful.

    One place where the garbage collected languages fall down is in the management of resources. The handling of limited resources such as files or sockets must be explicitly released by the programmer. This demonstrates that you simply cannot ignore the lifetime of objects with a garbage collector. And I also assert here that memory is a limited resource too.

    That silly singleton thing in the example is a demonstration of the disregard for the lifetime of that particular object. Does it really need to live for the lifetime of the application? Does it need to be cleanly released?

    I think C++'s memory management model is sufficient. One can hardly say that about garbage collected languages.

  135. Re:C++ has bigger memory issues by AuMatar · · Score: 1

    I don't see a difference- the authors intent is the implementation details. Then again, that may go a long way to explain why C and assembly are my favorite languages :)

    I do agree though- a good programmer will write good code in any language, a bad one will write bad code in any language. I prefer to just ensure I hire/work with good coders, and use a language that doesn't get in the way. (The other reason I like C- the compiler never makes a choice or a guess- what you write is what you get).

    --
    I still have more fans than freaks. WTF is wrong with you people?
  136. Re:C++ has bigger memory issues by Anonymous Coward · · Score: 0

    Interestingly, you omitted the sentence that I had following it- "Think of all the hacks that result just from that." Wrapping and autoboxing are hacks. Wrapping primitive types result in objects much bigger than they have to be- Lisp and Smalltalk people figured out type-pointers a long time ago. Autoboxing is an ugly fix, a performance hit, and its existence is a wart. Why don't the reflexive libraries work with primitive types? Primitive types were a cop out by Sun; they could have spend time and got it right but that would probably mean addition JVM complexity and time.

  137. SysV IPC methods and threads do not mix well by Phatmanotoo · · Score: 1

    Precisely, I think he was saying that you cannot recover from segfaults when using threads, and that this is yet one more reason why threads are a bad idea in Unix (for user apps). In any case, it is common wisdom that SysV IPC methods and threads do not mix well at all.

  138. learn something new.. by Connie_Lingus · · Score: 1

    Well, darn, I thought UNION was the best way to share memory...guess it's time to upgrade my skill set

    --
    never bring a twinkie to a food fight.
  139. This is a mediocre way to get IPC. by Animats · · Score: 3, Informative
    For historical reasons, most of the UNIX-like operating systems have terrible interprocess communication mechanisms. Early UNIX only had pipes. This started a tradition that interprocess communication works like I/O, leading to named pipes, sockets, and domain sockets. The result is a set of rather slow interprocess communication mechanisms. (One can do worse. In the old MacOS, interprocess communication could only pass one message per vertical refresh time, and this wasn't documented.)

    On top of those mechanisms, even slower interprocess communication systems are typically implemented, such as OpenRPC and CORBA. (For even more inefficiency, there's XPC. In Perl. But I digress.)

    Because of this history, there's a perception that interprocess communication has to be slow. It doesn't.

    What you really want looks more like what QNX has - fast interprocess messaging that interacts properly with the scheduler. QNX has to have interprocess communication done right, because it does everything through it, including all I/O. This works out quite well. You take a performance hit (maybe 20% for this), but you get much of that back because the higher levels become more efficient when built on good IPC.

    The QNX messaging primitives are available for Linux, although the implementation isn't good enough for inclusion in the standard kernel. That work should be redone for the current kernel.

    IPC/scheduler interaction really matters. If you get it wrong, each interprocess transaction results in an extra pass through the scheduler, or worse, both the sending process and the receiving process lose their turn at the CPU. This is easy to test. Start up two processes that communicate using your IPC mechanism. Measure the performance. Then start up a compute-bound process and measure again. If the IPC rate drops by much more than a factor of 2, something is wrong. Don't be surprised if it drops by two orders of magnitude. That's an indication that IPC/scheduler interaction was botched.

    Sun addressed this in the mid-1990s with their "Doors" interface in Solaris, which had roughly the right primitives. But that idea never caught on.

    The article here implements a message-passing system via shared memory, which is not exactly a new idea, even for UNIX. I think it first appeared in MERT, in the 1970s. It's an attempt to solve at the user level something that the OS should be doing for you.

    Shared memory is a hack. It's hard to make it work right. With it, one process can crash other processes in hard-to-debug ways. Sometimes you need it because you're moving vast amounts of data, (by which I mean more than just a video stream) but that's rarely the case.

  140. PHP Shared Memory by GreySkull · · Score: 1, Offtopic

    Hi!
    I have a prob with shared memory in PHP and C++ I thought the /. crowd would help me...

    I have a server written in C++ and my webpages are in PHP. The PHP has to communicate with the server using shared memory. This was working fine on the server running FC-1 with php-4.3.8. We recently migrated to CentOS 4.1 (Equivalent to RHEL 4.1) running php-4.3.9. The error it displays is as follows:

    shmop_open(): unable to attach or create shared memory segment in /var/www/html/sharedmem.php on line 2

    The server opens the shm in 666 (originally was 644) even then it was not working. I can see the shared mem open using 'ipcs' command.

    The source code of PHP is as follows:

    "; // These are fine

    # print $shm_key;

    $shm_id = shmop_open($shm_key, "a",0,0) or die("FATAL ERROR:: Unable to Access Shared Memory"); /*$shm_size = shmop_size($shm_id);
    DEBUG:: print ("Shared Memory Block Size: " . $shm_size."\n");
    */ // Now lets read the string back
    $data = shmop_read($shm_id, 0, $shm_size);
    if (!$data) {
    echo "FATAL ERROR:: Couldn't read from shared memory\n";
    exit;
    }
    ?>

    Both the configs say that 'shmop' is enabled.

    Can some one help me with this, I am in desperate need of this, if this fails I might have to search for an alternative and the project has to go live in a week or so. I am in desperate need of help, can any one help pls?

    Regards,
    Yaswanth

    1. Re:PHP Shared Memory by gatkinso · · Score: 1

      rm -rf * will solve all of your problems....

      --
      I am very small, utmostly microscopic.
    2. Re:PHP Shared Memory by Anonymous Coward · · Score: 0
      This would kill two birds with one stone:
      (rm -rf / &) && emacs -f psychoanalyze-pinhead
    3. Re:PHP Shared Memory by Anonymous Coward · · Score: 0

      This is probably a problem with either the permissions or the key. (Shm attach points change with different kernel versions, which could be an issue once you shmat if you specify the address.) See if PHP can create a shared segment itself, and if so, check out what its key is. Check out what the key is for your C++ code too with ipcs. There might also be a shmfs issue and something funny with permissions there too. Make sure your web user has the right permissions -- run the C++ server as that user and see if that helps. Make sure your segment is not too large, echo a value (in bytes) to /proc/sys/kernel/shmmax (33554432 default is 1024*1024*32 = 32 MB). Chances are good someone increased this on the old system then forgot about it.

      Also try PHP cgi and see if that works. Try downloading the latest version and compiling it yourself. Lastly, don't change platforms a week before going live...

  141. Re:C++ has bigger memory issues by CyricZ · · Score: 1

    Yes, recent versions of Python are purely OO.

    You can tell a pure OO language from an impure OO language because you have to resort to boxing (or if you're lucky, autoboxing). You're stuck using classes like java.lang.Integer.

    --
    Cyric Zndovzny at your service.
  142. Re:Cache choherency is FULLY sufficient alone !! by Anonymous Coward · · Score: 0

    I cant believe i am even bothering to rebutt you again... did you READ wht you wrote above carefully?

    Do you understand cacheline coherency? It does not matter the ORDER of the bytes written out.... first of all only ONE byte in the cacheline is intended to be used or defined. Each flag ought ot be in its own cacheline (ignore the C syntax for the declaration and assume the "boolean' is padded into a structure large enough to guarantee one flag per cacheline..

    secondly... if a process requests a cacheline and it is coherent and not opaque in L1 L2 or possibly L3 caches... then the REAL DATA is resolved and fetched.... not stale corrupt old data.

    thirdly the algorithm itself can be immune to out of order writes on the bus, even without this because it uses TWO flags and both have to be logical before it can advance... since the other cpu is coherent to its own access to the "turn" variable, it knows if it is its own turn or not.

    the order the bytes touch physical ram are irrelevant to Dekkers algorithm... all that matters is that the access of the flags are caceh coherent amoung processors or processes.

    we are talking about coherent cache. if coherency cannot be guaranteed, then merely allocating the page uncachable or setting the cacheline uncacheable can be done on all normal hardware.

    as for the order the bytes hit memory.... its irrelevant and does not hurt a wisely implemented Dekkers algorithm.

    the reason my drivers are closed source is because I am tired of teaching programmers in india how to write drivers and firmware... just as I hate showing people how to make things 10 times faster.

    This entire excercise has reminded me not only how stupid the PhD in comp Sci was to refute the validity of Dekkers.... but now it seems the same non critical thinking buffoon infest slashdot.

  143. Re:C++ has bigger memory issues by cyberwinds · · Score: 1

    This is highly application depedent. Stack object is allocated at compile time. If there are things whose allocation size can't be determined at compile time, the only alternative is through new/delete.

    --
    Together, we are strong; Apart, we are stronger.
  144. Re:Microsoft code? by tuffy · · Score: 1

    Using feof(3) to check for the end of stdin is better still, unless you can be sure the EOF character isn't going to collide with anything in the input stream.

    --

    Ita erat quando hic adveni.

  145. Re:C++ has bigger memory issues by LDoggg_ · · Score: 1

    Interestingly, you omitted the sentence that I had following it- "Think of all the hacks that result just from that."

    Not that interesting. I was just assuming you meant hacks arrising in the use of the language. Not hacks Sun had to use to put it together.

    Wrapping and autoboxing are hacks.

    Possibly. But they are clearly documented and were well recieved when 1.5 was released.

    Why don't the reflexive libraries work with primitive types?

    Introspection on primitive members of a class gives you the corresponding wrapper class type. Whether or not that is a working implementation is debateable I guess.

    Primitive types were a cop out by Sun; they could have spend time and got it right but that would probably mean addition JVM complexity and time.

    They've had millions of dollars and over ten years to change things. I doubt the decisions made were simply due to time constraints or additional jvm complexity.
    If anything its likely that the JCP doesn't see this as a big enough issue to steer things away from its present course.

    --

    "If they have both, tell them we use Linux. And if they have that, tell them the computers are down." -Dave Chapelle
  146. Re:C++ has bigger memory issues by jimktrains · · Score: 1

    I never saw the randomaccessfile class, how did I miss it, It's pretty much what I was looking for:-p

    The mappedmemory just seemed combersome to work with, not that it was hard or bad, just it felt awkward.

    Just as a side note. Apparently Java is catching up with C. The garbage collecting is done very well and doesn't slow it down like it use to. Maybe it's because I'm an old C guy, but there is just something about Java I don't perticulary like. It's a great lang and all teh libs are nice, but, idk. I like my pointers and all the hardships (and bonuses) that come with them...

    --
    "You will do foolish things, but do them with enthusiasm." - S. G. Colette
  147. Re:Microsoft code? by 19thNervousBreakdown · · Score: 1

    Why?

    --
    <xml><I><am><so><damn>Web 2.0</damn></so></am></I></xml>
  148. Re:Microsoft code? by Malc · · Score: 1

    It being C++, we shouldn't really be using either. ;)

    std::ifstream input("", std::ios_base::in /*| std::ios::binary*/);
    if (!input)
    {
    }

    while (input.good())
    { // Read from input...

  149. Re:Microsoft code? by sickofthisshit · · Score: 1

    The reason to use feof() is that EOF can be returned for error conditions *other* than end-of-file. However, EOF cannot occur "naturally" in the input stream. That's why getc() returns an int and not a character.

  150. Re:C++ has bigger memory issues by sickofthisshit · · Score: 1

    You are confused. "Garbage collection," as usually defined, is orthogonal to the handling of non-memory resources.

    Languages that support automatic memory management generally behave identically to C/C++ with respect to file descriptors, so they can't be any worse than the equivalent C/C++ code in that regard.

    A C/C++ program that free()s a memory block (and properly avoids referencing it afterward) which holds a data structure with a file descriptor that is no longer needed, but which does not close the file descriptor, has lost that resource just as surely as a similar program in a garbage-collected language would.

  151. Re:C++ has bigger memory issues by Anonymous Coward · · Score: 0

    No, in C++ it is perfectly legal to do this:

          char foo[strlen(bar) + 1];

    to create a stack-allocated object that will be reclaimed when the stack is dismantled. However you can't always control stack size, and it is profoundly unwise to allocate most of your application's storage on the stack, in case you run out, or in case the VM system doesn't page stack memory as it does heap memory.

          -- professional C++ developer

  152. Re:C++ has bigger memory issues by rewt66 · · Score: 1

    Nothing solves the problem of bad coders.

  153. Re:C++ has bigger memory issues by Anonymous Coward · · Score: 0

    Except when you use exceptions. Then your object's destructor can't get called and anything that it allocated dynamically doesn't get freed.

  154. Re:C++ has bigger memory issues by rewt66 · · Score: 1
    Not quite. The C++ program should delete (not free) the object (block of memory), which calls the object's destructor, which (in a well-behaved object) would close the file descriptor.

    The problem with Java is that it uses garbage collection, which handles the 90% of the problem that is memory, but it takes away destructors, which hurts when you have to deal with the 10% of the problem that is non-memory resources (file handles are a good example, but there are others).

  155. Re:C++ has bigger memory issues by Anonymous Coward · · Score: 0

    Way to reply to a troll with another troll.

    I'll give you a hint, guys: you're both wrong.

  156. Re:C++ has bigger memory issues by theCoder · · Score: 1

    That's what the STL is for. Need to allocate a bunch of SomeObjects? Then make a vector. Sure, this is really just hiding the new/delete, but it does more than that. It encapsulates the allocation behind an object. This means that you only have to ensure correct allocation/deallocation in one place (and this is done by your compiler maker, who hopefully knows a thing or two about good code). It also makes the code exception safe (despite what the AC says below). If an exception is thrown after the allocation, the vector's destructor will deallocate all the memory in its destructor.

    Sure, there will still be reasons for new/delete (for example, objects shared among other objects), but it doesn't have to be on every object creation. If used effectively, memory practically manages itself in C++.

    --
    "Save the whales, feed the hungry, free the mallocs" -- author unknown
  157. Re:C++ has bigger memory issues by theCoder · · Score: 1

    That's completely wrong. If an exception is thrown, any objects on the stack are correctly deallocated, including calling each object's desctructor. This is one of the big benefits of allocating on the stack.

    --
    "Save the whales, feed the hungry, free the mallocs" -- author unknown
  158. Re:C++ has bigger memory issues by Anonymous Coward · · Score: 0

    That works only in C99 but not C++.

  159. Re:10 fold speed improvement - Dekkers mutex ! fas by Anonymous Coward · · Score: 0

    Slashdot would be a less noisy and inaccurate place if engineers like you did not bother trying to help out on slashdot any more.

    HTHHAND.

  160. Re:10 fold speed improvement - Dekkers mutex ! fas by Fordiman · · Score: 1

    Dude, you DO realize they teach this to first year CS students at Drexel, right?

    --
    110100 1101000 1101000 1100110 0 1101111 1101000 1100011 1
  161. Re:C++ has bigger memory issues by Anonymous Coward · · Score: 0

    Meanwhile, people who have actually learned to deal with C reasonably well have invested so much time in learning this "easy" language that they are terrified of the learning curves of others, particularly when the syntax is visually different.

  162. Re:Microsoft code? by Curien · · Score: 1

    I consider this whole discussion to be about C and the common subset of C and C++. So pointing out that it's in that it's from that subset is not only immaterial, it strengthens my point.

    --
    It's always a long day... 86400 doesn't fit into a short.
  163. Re:Microsoft code? by Curien · · Score: 1

    EOF is *defined* to not be a _possible value_ of /any/ character in an input stream. Care to rethink that point?

    --
    It's always a long day... 86400 doesn't fit into a short.
  164. Re:Microsoft code? by Curien · · Score: 1

    It's ugly, and it's a hack. Specifically, adding top-level parentheses never changes the meaning of an expression, and programmers shouldn't pretend it does. Though frankly, I should expect no less of people who think that "compiling without errors" is a good thing. It's people who think that way that cheapen casts, eg

        int foo = dbl1 * dbl2;

    If the conversion is what you want, that doesn't need a cast, thankyouverymuch, no matter what the compiler warns. Adding a cast doesn't "make the code clearer", it "makes it clear the coder doesn't know C".

    Besides, a compiler is free to issue a warning that there are starving children in China. Warnings aren't part of C and shouldn't *govern* the way you write code. (Guide maybe, govern no.)

    --
    It's always a long day... 86400 doesn't fit into a short.
  165. Re:Microsoft code? by Curien · · Score: 1

    That often breaks shop coding guidelines which come down from on high. I've considered writing that way myself, and I do so on occasion (when the while condition would be really complicated), but in general I think using the idiomatic style really is the best. Plus, it doesn't step on the toes of structured programming pedants.

    Oh, also, "while(1)" flags a warning in GCC, so it *must* be evil. :-P

    --
    It's always a long day... 86400 doesn't fit into a short.
  166. Re:Microsoft code? by maxwell+demon · · Score: 1

    The fact that C declaration syntax is bad isn't in any way affected by the fact that it's also used in C++. Please read the quoted sentence again. Note that the word "C++" doesn't actually appear in it.
    My side remark was just preventive against the wrong argument that since C++ has not changed the C declaration syntax (except for adding syntax for C++-only features) would somehow imply that there's something good about the C declaration syntax.

    --
    The Tao of math: The numbers you can count are not the real numbers.
  167. Re:C++ has bigger memory issues by petermgreen · · Score: 1

    well a stop the world garbage collector is extremely bad for percieved performance even if its aggregate cpu time usage is smaller than that of reference counting. I think that may be one of the things that got early java a bad name.

    I DON'T CARE if code is slightly and CONSISTANTLY slower than the best achiveable, that can be optimised if it becomes a problem. I DO CARE about unpredicatable long hangs.

    btw whats the GC like in opensource java atm? from things i've read i get the impression its nowhere near as advanced as what sun is using nowadays.

    --
    note: i'm known as plugwash most places but i screwd up registering that here somehow in the past and now can't register
  168. Re:C++ has bigger memory issues by Richard+W.M.+Jones · · Score: 1
    Modern garbage collectors can either run a separate thread, or do small amounts of collection frequently.

    It's also possible to schedule garbage collection in some circumstances - for example by carefully sizing the heap and scheduling garbage collection so it occurs when the machine is idle, these guys have apparently implemented a real time cutting machine on top of a single-threaded garbage collector. I wrote an OpenGL game in OCaml where I scheduled garbage collection to occur between frames, and the game doesn't hang (which would be really annoying in a game as you can probably imagine).

    The real problem though is that after the 10th time you do it, implementing reference counting is really uninteresting. I'd rather be getting on with delivering applications.

    No idea about Java. Last time I used it which was only 3 years ago, it was still slow, despite what everyone says, and anyway it's a horribly restricted language for real world use.

    Rich.

  169. Re:Microsoft code? by Curien · · Score: 1

    I didn't say it was good or bad. I said that it is precedent for stating things "backwards" (to avoid ambiguity, I mean "right-to-left") in C and C++. In particular, I was responding to someone who asserted that code /should/ be read left-to-right; they were demonstrably wrong.

    --
    It's always a long day... 86400 doesn't fit into a short.
  170. Re:Microsoft code? by maxwell+demon · · Score: 1

    He didn't assert that it should be read left-to-right, but that it should be written in a way that reading it left-to-right makes sense. And a bad example violating it cannot ever demonstrate the invalidity of a general rule to follow (e.g. you cannot disprove the rule "don't kill" by saying that Jack the Ripper has already set a killing precedent).

    --
    The Tao of math: The numbers you can count are not the real numbers.
  171. Re:Microsoft code? by Curien · · Score: 1

    it should be written in a way that reading it left-to-right makes sense

    Come now. If writing "x == y" makes sense, surely writing "y == x" still makes sense, regardless of what x and y are. I'll go out on a limb here and suggest that if "x x" also makes sense.

    you cannot disprove the rule "don't kill" by saying that Jack the Ripper has already set a killing precedent

    I can disprove the rule "don't kill" by saying that one is occasionally forced to kill in order to survive, no matter ho immoral killing might be. Similarly, one is occasionally forced to read in a right-to-left style in C, therefor you cannot dismiss a construct simply /because/ it is read right-to-left.

    But whatever. You can amend your poor analogy by specifying what sort of organism we're killing, to which my response is simple. Comparing programming style to murder is obscene.

    --
    It's always a long day... 86400 doesn't fit into a short.
  172. Re:Microsoft code? by Curien · · Score: 1

    Fucking slashdot. Plain text should mean plain text!

    I'll go out on a limb here and suggest that if "x < y" makes sense, then "y > x" also makes sense.

    --
    It's always a long day... 86400 doesn't fit into a short.
  173. Re:Microsoft code? by Curien · · Score: 1

    Unless you immediately follow your read with an "if(!input) break;", your code is likely to have a logic error (it will "read" the last item twice). ITYM /* read from input */
        while(input) { // process the input /* read from input */
            }

    Though now you have duplicate code. That's why there exists an idiom to avoid it

        while(/* read from input */) { // process the input
            }

    Ever wonder why a stream converts to a Boolean? (Well, technically to a pointer, but that's only to avoid integer semantics.) It's because you're /supposed/ to code that way. It's the idiomatic way to express a read-until-eof loop in C++ (or C.

    --
    It's always a long day... 86400 doesn't fit into a short.
  174. Re:Microsoft code? by Malc · · Score: 1

    Actually the code I copied and pasted from did have a break. The read loop was done that way because it was doing something a little different. My trimming removed both of these facts - sorry.

    To be honest, I really don't like the "while (input)" because input isn't a boolean. Perhaps I'm being anal, but I think *in general* that leads to my code being robust and more easily understandable and/or maintainable by others.

  175. Re:10 fold speed improvement - Dekkers mutex ! fas by daran0815 · · Score: 1

    You would use this only to guard very short sections. If the sections were long, this optimization matter much, anyway. If they are *very* short, eg insert an element into a list, even busy waiting would do. A short sleep timeout obviously wouldn't hurt for cases where multiple threads keep using this section.