Slashdot Mirror


Threads Considered Harmful

LBR9 writes "James Reinders compares native threads with the goto statement so famously denounced 40 years ago by Edsger Dijkstra. Paraphrasing Dijkstra, he says they both 'make a mess of a program,' and then argues in favor of a higher level of abstraction. A couple of people commenting on the post question whether or not we should be even be treading into the 'swamp of parallelism,' echoing the view recently espoused by Donald Knuth."

266 comments

  1. No threads? by Anonymous Coward · · Score: 5, Funny

    Alright, then all responses to this article need to fall under this one post.

    1. Re:No threads? by A+beautiful+mind · · Score: 1

      exit(0);

      --
      It takes a man to suffer ignorance and smile
      Be yourself no matter what they say
    2. Re:No threads? by Anonymous Coward · · Score: 0

      ?SYNTAX ERROR
      READY.
      []

    3. Re:No threads? by joebp · · Score: 1

      It's a nice illustration that exit(3) is by definition not reentrant.

    4. Re:No threads? by Anonymous Coward · · Score: 0

      ZOMG, I'm posting in a thread. What possible harm could befall me?

    5. Re:No threads? by Hognoxious · · Score: 1

      fork you!

      --
      Confucius say, "Find worm in apple - bad. Find half a worm - worse."
    6. Re:No threads? by Anonymous Coward · · Score: 0

      pthread_exit(NULL);

    7. Re:No threads? by jo42 · · Score: 1

      Gads, get it right:

      you = fork();

    8. Re:No threads? by Anonymous Coward · · Score: 0
      Sigh, yet another to the long list of obsolete skills that I've acquired at one time or another.

      Rotary dialing, Ditto Machines, GOTO statments, ERROR Levels, Structured Programming, PASCAL

      Now Native Threads

      Protect the environment! Use Green threads !

    9. Re:No threads? by Codifex+Maximus · · Score: 1

      I don't consider these: Structured Programming, PASCAL obsolete.

      We need more structure in our programming not less; these days there's too much crappy unstructured code. Even object-oriented programming can benefit from structure - otherwise, it begins to look too much like goto style. PASCAL is just a great example of structure.

      --
      Codifex Maximus ~ In search of... a shorter sig.
    10. Re:No threads? by Anonymous Coward · · Score: 0

      we = fork();

      FTFY

  2. Probably the first relevant "first post" I've seen by Delusion_ · · Score: 1

    Now if only I could get rid of these handles.

  3. Especially the ones with goatse links by Huntr · · Score: 1

    Yikes!

  4. In other news by Anonymous Coward · · Score: 0

    Donkey dick considered harmful.

    1. Re:In other news by Anonymous Coward · · Score: 0

      Yer mum said it was fine.

    2. Re:In other news by Anonymous Coward · · Score: 1, Funny

      Donkey dick considered harmful. Sir, as a lady donkey or "jenny" I find that statement offensive. Donkey dick is not harmful and in fact I would not be here today without it. I personally find it appropriately sized for its intended function and not at all dangerous when used properly.
    3. Re:In other news by History's+Coming+To · · Score: 1

      My donkey dick failed and my chicken loop came off. Nearly killed me. (Seriously...they're kitesurfing terms, look it up.)

      --
      Please consider this account deleted, I just can't be bothered with the spam anymore.
    4. Re:In other news by NateTech · · Score: 1

      We'll believe you if you promise to never mention it in public again.

      Every time you mention your donkey dick, God kills a kitten.

      --
      +++OK ATH
  5. Some people can handle threads... by Anonymous Coward · · Score: 0

    and some can't. My programs were readable with goto. If yours were not, that's your own fault.

    1. Re:Some people can handle threads... by EnglishTim · · Score: 1

      My programs were readable for me with goto. If yours were not, that's your own fault.

      There. Fixed that for you.

    2. Re:Some people can handle threads... by trolltalk.com · · Score: 1

      My programs were readable for me with goto. If yours were not, that's your own fault.

      There. Fixed that for you.

      ... and how does this differ from programs that don't use goto? Or code you haven't looked at in over a year?

      Most non-trivial programs also need the context they were written in, to be fully grokked.

    3. Re:Some people can handle threads... by jythie · · Score: 1

      Having seen some pretty messy 'correct' solutions that can be implemented so much cleaner with a goto,... no, I would say the GP was correct. A well used goto is quite readable and can be far, far simpler then the messy workarounds using higher level structures.

      One of the things I look for in interviewing a programer is their perspective on 'goto'... if they claim it should never be used ever for anything by anyone in any situation that is generally a black mark against them.

    4. Re:Some people can handle threads... by everphilski · · Score: 2, Interesting

      I'm an aerospace engineer, but write code 40-60% of my workday. Essentially between a FORTRAN/C++ compiler and Excel, those are my design tools. In the last 4 years (I'm relatively fresh out of college), I've used GOTO once. And you are right, it's a useful tool in very specific situations, in FORTRAN. However in C++ with object-oriented programming, I have yet to see a case, in the work I do anyways, where it would make something more concise.

    5. Re:Some people can handle threads... by jythie · · Score: 1

      The place I usually use goto (an I think I have used it a total of 2 or 3 times in my career) is when interfacing C++ code into c libraries.

      It can be really useful for jumping down to a cleanup section of a function where some things need to be manually shut down upon failure of the main function. In these situations there are OOP (or even procedural) ways to also handle it but they tend to require either some rather iffy wrapper classes or complex parameters being passed around. Example:

      foo()
      {
      library_thingie
      library_thingie
      library_thingie

      do stuff that can fail horribly
      goto cleanup;
      do more stuff

      cleanup:
      undo_library_thingie
      undo_library_thingie
      undo_library_thingie
      }

      Now, within OOP you could wrap up the library_thingies within locally scoped objects and the compilier will insert the needed deconstructors but for small cases this ads a lot more complexty and indirrection making the code harder to read.

      Within procedural you could change it too:

      foo()
      {
      library_thingie
      library_thingie
      library_thingie

      bar(library_thingie,library_thingie,library,librar_thingie);

      undo_library_thingie
      undo_library_thingie
      undo_library_thingie

      }

      but you can imagine how badly that can scale depending on how much can get passed around.

      it is also possible to make the things global (it's own type of evil) or use heavily nested if/then/else statements but that can also become very complex and difficult to read.

    6. Re:Some people can handle threads... by twistedcubic · · Score: 1

      I've used goto once in C++ code. I remember trying to implement a very, very tricky combinatorial algorithm when I was very tired. I reworked the algorithm on paper, saw that a goto would simplify one part considerably, looked up the proper usage of goto, and wrote it in. The algorithm worked correctly for the first time. I'm sure there still is a problem, but this particular algorithm should crash when implemented incorrectly, and I still haven't fixed it yet because I'm still shocked that using goto solved the problem when I couldn't figure it out otherwise. Of course, I will remove the goto when I have to share the code, but I'm not there yet :)

    7. Re:Some people can handle threads... by SanityInAnarchy · · Score: 1
      Ok, first of all:

      but you can imagine how badly that can scale depending on how much can get passed around. You're using a language that supports goto -- surely it supports pointers?

      More relevantly, why wouldn't this work?

      def foo
        library_thing1
        library_thing2
        library_thing3
       
        begin
          do stuff that can fail horribly
          do more stuff
        ensure
          undo_library_thing3
          undo_library_thing2
          undo_library_thing1
        end
      end
      I probably wasn't understanding quite what you needed there. I realize some people see exceptions as a kind of goto, but it is a bit more structured.

      And when you're doing three library calls already, it doesn't seem like a "small case" anymore.
      --
      Don't thank God, thank a doctor!
    8. Re:Some people can handle threads... by sjames · · Score: 1

      In some cases, the OOP way scales really badly. Lets consider a function that must perform a series of operations that can fail where each operation depends on the previous operation.

      If you make all of the behind the scenes use of destructors and such explicit you get:

      object1_init
      if error goto cleanup:
      object2_init
      if error goto cleanup
      object3_init
      if error goto cleanup

      do stuff

      cleanup:
      if object3_inited destroy object3
      if object2_inited destroy object2
      if object1_inited destroy object1
      return

      You just don't see all of that hidden behind a simple looking if error return

      Explicit use of goto can make such unwinding operations quite clean and efficient, particularly when the function must unwind in the successful case as well:

      object1_init
      if error goto cleanup1:
      object2_init
      if error goto cleanup2
      object3_init
      if error goto cleanup3

      do stuff

      cleanup3:destroy object3
      cleanup2: destroy object2
      cleanup1: destroy object1
      return

      Notably, since we can know based on the logical flow if an object has been initialied or not, we can skip the condition checking and just do the right thing.

      Notably, MANY programmers use the semantic equivilant of a goto daily and don't even think about it because it looks like return. Behind the scenes, a return in mid-function looks just like goto. when using newer languages, catching an exception ALSO looks like a goto behind the scenes. Actually it looks like a chain of if error goto in order to unwind the call stack.

      Notably, a big while loop that is normally executed once but exists to handle retries with the use of continue is just a baroque way to write if failed goto retry. It isn't clearer at all. The while approach is doubly lame if it normally exist on a break after running once or if it uses a boolean that is set by if error continue else allswell=true.

      I fully agree that GOTO as it was commonly used when "goto considered harmful" was written was indeed harmful. ESPECIALLY when it was used as a substitute for else and every if ends in a goto.

      When goto is used for error (exception) handling, it can make things much clearer and more efficient. I have also found a few cases where retry operations strongly call for a goto. It IS possible to contort the rest of the logic to stick it inside a big while not done loop, but the contortions make everything else anti-intuitive for just about anyone all for the sake of obsessively avoiding a single well considered goto.

      Read properly, "goto considered harmful" tells the programmer to think carefully about that goto he is about to use. Is there a better way? Is it papering over a fundamental flaw or inelligance in the logic? Will it violate the principle of least astonishment? Is it jumping over an else in disguise? Is it trying to violate scope? (jumping out of a scope is one thing, jumping into a scope is a problem).

      If the answer to those questions is no, then use the goto and get on with life.

      To me, threading is similar. Using threads because you can is quite harmful. Using threads that shouldn't interact instead of fork is inviting problems. Using threads interacting through semaphores and mutexes to the point that they necessarily operate serially is a special kind of bad. Some operations are intrinsically serial.

    9. Re:Some people can handle threads... by jythie · · Score: 1

      In the case I was thinking, the 'libarary calls' were obtaining the needed handlers to actually work with the data. There were quite a few of them that have to be set up and destroyed. These handlers could be passed around as parameters but there was an increasing number of them and passing them around was adding significant complexity.

      Unfortunately exceptions are not always an option and may not be thrown when you want to, esp if the library you are interacting with does not throw exceptions. Even then an exception only works if you have a way to catch the needed calls when unrolling the stack.

      Sure you can wrap up the c handlers in c++ objects which then have automagic destructors, but that is a lot of extra layers and code just to get around using a goto.

    10. Re:Some people can handle threads... by SanityInAnarchy · · Score: 1

      There were quite a few of them that have to be set up and destroyed. These handlers could be passed around as parameters but there was an increasing number of them and passing them around was adding significant complexity. Wrap them in an object -- one object. That's not a lot of complexity.

      Unfortunately exceptions are not always an option and may not be thrown when you want to, esp if the library you are interacting with does not throw exceptions. Presumably they do give you an error at some point, right?

      begin
        result = stuff_that_can_fail_horribly
        throw 'It failed horribly' if result.nil?
        do_more_stuff_that_throws_proper_exceptions
      ensure
      ...
      end

      Even then an exception only works if you have a way to catch the needed calls when unrolling the stack. When would you not?

      Oh, by the way -- "ensure", in Ruby, is a block which is guaranteed to run after the "begin" block finishes, exceptions or not. It seems to be the absolutely perfect, logical fit for what you're trying to do.

      Sure you can wrap up the c handlers in c++ objects which then have automagic destructors, but that is a lot of extra layers and code just to get around using a goto. I still don't see how the goto is easier, in this case. Seems to me, you end up with the exact same problems -- when does that goto happen? How do you make sure it gets called, and how do you make sure you catch the error condition properly?
      --
      Don't thank God, thank a doctor!
    11. Re:Some people can handle threads... by StarvingSE · · Score: 1

      Try, catch, finally was invented for this reason....

      foo()
      {
          try {
          library_thingie
          library_thingie
          library_thingie

          do stuff that can fail horribly

          do more stuff

          } catch {
                exception/error handling
                undo_library_thingie
                undo_library_thingie
                undo_library_thingie
          }
      }

      --
      I got nothin'
    12. Re:Some people can handle threads... by techno-vampire · · Score: 1
      Of course, I will remove the goto when I have to share the code


      Why bother? It works, so don't fix it. Just make sure there's a comment at the goto saying why it's there and where it goes, and another one at the destination documenting where the goto is, and let it go at that. In general, a goto is bad if and only if it's not clear where it goes, or if it's not clear what the destination's label is for.

      --
      Good, inexpensive web hosting
    13. Re:Some people can handle threads... by Anonymous Coward · · Score: 0

      I don't fully understand your example, so this may be the same thing. The place I still see goto used in C code(no C++ involved here) is in functions that acquire resources, and need to ensure that the resources are freed before the function returns. So you have a cleanup: label at the end that is just before all of your free(), unlock(), close(), etc. calls(see the Linux kernel for lots of examples). This is pretty clean, and ensures that you don't get resource leaks. I've used this many more than 2 or 3 times in my career, and I don't see anything really wrong with it. The problem is that it limits to a certain extent other types of things that people like to do, such as returning out of the middle of a function.

    14. Re:Some people can handle threads... by jythie · · Score: 1

      screw it, screw slashdot, screw the lame filter.

      I couldn't get it to accept the post due to the various code-like examples. something about not enough characters per line.

    15. Re:Some people can handle threads... by jythie · · Score: 1

      try/catch only works when the library you are using has functions that throw exceptions.

      many system (and c) libraries do not throw anything and often have functions specifically marked NOTHROW.

    16. Re:Some people can handle threads... by SanityInAnarchy · · Score: 1

      Ugh, I hate that.

      I haven't yet found a way around it, other than pretty much completely removing the code samples.

      --
      Don't thank God, thank a doctor!
    17. Re:Some people can handle threads... by ObjetDart · · Score: 1

      I think that's not quite what you meant to do. How about this instead:

      foo()
      {
              try {
              library_thingie
              library_thingie
              library_thingie

              do stuff that can fail horribly

              do more stuff

              } catch {
                          exception/error handling
              } finally {
                          undo_library_thingie
                          undo_library_thingie
                          undo_library_thingie
              }
      }

      --
      I read Usenet for the articles.
    18. Re:Some people can handle threads... by jythie · · Score: 1

      Well, one positive thing worth saying though was I think you were spot on with the Ruby solution.

      goto's main use is when interfacing directly with ANSI C libraries that do not allow for things like exception handling or automatic destructors. Or situations where the 'common case' for/while/do/if/case do not fit very well (since those are all common cases of goto wrapped up with pretty synatx.. but do not represent the full usage).

    19. Re:Some people can handle threads... by StarvingSE · · Score: 1

      The OP is using C++, which doesn't support finally blocks. I also assumed that in this example cleanup code was only to be run in the event of an error.

      --
      I got nothin'
    20. Re:Some people can handle threads... by ObjetDart · · Score: 1

      Alrighty, guess I'm too stuck in a C# frame of mind. But to be fair, the OP's code snippets have the cleanup code being executed in both success and failure cases. Plus you did say "try, catch, finally"... ;)

      --
      I read Usenet for the articles.
    21. Re:Some people can handle threads... by try_anything · · Score: 1

      Sure you can wrap up the c handlers in c++ objects which then have automagic destructors, but that is a lot of extra layers and code just to get around using a goto. An RAII (destructor-based solution) would save your can if an unexpected exception is thrown from your code or from library code, but most importantly, it would be idiomatic for the language you're writing in. It might require a few more lines of code, but a typical C++ programmer will immediately and correctly grasp what the code does. Whereas, if you do something unexpected like using goto, a typical C++ programmer will assume there was a reason you couldn't use the idiomatic construct, and they will get distracted trying to figure out why you used goto instead.
    22. Re:Some people can handle threads... by Codifex+Maximus · · Score: 1

      Use PASCAL for your code examples:
      { = BEGIN
      } = END

      Problem solved. >:)

      --
      Codifex Maximus ~ In search of... a shorter sig.
    23. Re:Some people can handle threads... by CableModemSniper · · Score: 1

      Sure you can wrap up the c handlers in c++ objects which then have automagic destructors, but that is a lot of extra layers and code just to get around using a goto.
      Let me preface this by saying I don't think gotos are always "bad", that said, I don't think they're the best solution for this example when writing in C++. Extra layers, yes (but mostly negligible), but extra code? This is why we have libraries. To wit:
      def foo
      library_thing1
      ScopeGuard u1 = MakeGuard(boost::bind(undo_library_thing1));
      ...
      stuff that can go horribly bad
      ...
      end

      I apologize for the lack of indentation, I just couldn't get it right.

      You don't even need to create a new class if you don't want to, and the setup and teardown are right next to each other, so you don't have to scan down to the bottom of the function to be sure you cleaned up after yourself (goto or no).

      1. scope guard: http://www.ddj.com/cpp/184403758
      2. boost::bind: http://www.boost.org/doc/libs/1_35_0/libs/bind/bind.html
      --
      Why not fork?
  6. How about "C++ threads considered harmful"? by krog · · Score: 4, Insightful
  7. Nothing New Under the Red Star by Bieeanda · · Score: 1

    Thread is bad? The Pernese could have told you that Long Intervals ago.

    1. Re:Nothing New Under the Red Star by spiffyman · · Score: 1

      Ahahaha, I get it! It's a Pern joke!

      --
      So you can laugh all you want to...
    2. Re:Nothing New Under the Red Star by spiffyman · · Score: 1

      I didn't read "The Pernese" on first load. I read "I" or something. So, rather than being informative and witty all at the same time, I'm just a jackass. My mistake.

      --
      So you can laugh all you want to...
    3. Re:Nothing New Under the Red Star by Bieeanda · · Score: 1

      For what it's worth, I think your response was funnier than mine.

    4. Re:Nothing New Under the Red Star by Anonymous Coward · · Score: 0

      Nudists think threads are bad too.

  8. I'm All For Getting Rid Of Threads, But... by rsmith-mac · · Score: 3, Informative

    I'm all for getting rid of threads, but what are you going to replace them with? Traditional functional languages may be the most obvious solution, but they're also among the most impractical of solutions. Is there anything else out there that can replace threading needs, without throwing out the book on programming? It seems like what we need hasn't been invented yet.

    1. Re:I'm All For Getting Rid Of Threads, But... by abigor · · Score: 2

      http://en.wikipedia.org/wiki/Tuplespace

      Threads only seemed to get really popular with Windows. Unix programming has typically always been multi-process with some form of shared memory. I've heard (and this is unconfirmed hearsay) that CreateProcess() on Windows is so heavyweight that they pushed for a comprehensive threading model instead.

    2. Re:I'm All For Getting Rid Of Threads, But... by Anonymous Coward · · Score: 0

      I always thought it made sense to combine threads with objects. Object-orientation was a big leap forward; it makes sense to encapsulate the runtime of the object as well as the data. This is how gadgets are in the real world - you don't have to worry about whether you turn on your mobile phone, iPod, and PDA all at once or one by one.

      Make the objects parallelizable, and let the environment decide whether to make them persistent or not. Stick them in the cache when they're needed - serialize them and store them when they're not.

    3. Re:I'm All For Getting Rid Of Threads, But... by plague3106 · · Score: 1

      Um, if what you've heard is true, why have threads been in Unix for a very long time?

    4. Re:I'm All For Getting Rid Of Threads, But... by hardburn · · Score: 1

      I've never been able to track down the link, but Microsoft Research did a study during Longhorn development showing that Win2000 used over 1000 cycles to start a process, while Linux used less than 100.

      The bad news for Linux is that its always had a brain damaged threading model. In other words, Windows has great threads because its process model sucks, and Linux has great processes because its threading model sucks.

      --
      Not a typewriter
    5. Re:I'm All For Getting Rid Of Threads, But... by abigor · · Score: 1

      Well, I recall Unix threads as being difficult and divergent depending on OS. I wrote threaded code on AIX, HPUX, and Solaris. I recall compilation difficulties on AIX (different version of cc required, if I recall) and on Solaris it was just plain difficult, using a library called thr_thread (I think). Trying to write cross-platform threaded code was a pain vs. just using fork().

      I later used pthreads, of course, and that was much easier, but multiprocesses always seemed to be "the way things were done" - all the server software forked to service requests or whatever, rather than used threads.

      On Linux, Linus's anti-thread stance was a reflection of prevailing Unix attitudes. Threading has always seemed like the red-headed stepchild of Unix multiprocessing.

      Meanwhile, threads were in NT from day one, for better or for worse.

    6. Re:I'm All For Getting Rid Of Threads, But... by arth1 · · Score: 1

      What I don't get is TFA's jump from "threads are bad" to "so they should be replaced with higher level of abstraction". That jump is quite illogical.

    7. Re:I'm All For Getting Rid Of Threads, But... by abigor · · Score: 1

      Agreed, that's what I heard too, but like you I couldn't find the reference.

      My major problem with threading is simply that it breaks "encapsulation", if you generalise that term beyond object orientation. Threads have access to everything in the process space, even those objects that you'd rather not have them know about. That's why tuplespaces appeal to me: put those objects that are supposed to be synchronised somewhere special for processes to access, and don't bother worrying about everything else.

    8. Re:I'm All For Getting Rid Of Threads, But... by Waffle+Iron · · Score: 2, Informative

      Um, if what you've heard is true, why have threads been in Unix for a very long time?

      In the early 90s, threads were the "next big thing". Around that time Java was being designed, so it ended up oozing in threadedness. Threads were tacked into Unix as an afterthought somewhere around that era to keep up with the latest fads.

      Windows NT was also created in those times. Since threads were seen as the way of the future, the design of Windows NT was heavily focused on threads, and that was touted as making the new OS more "modern". There was not a lot of emphasis on process spawning efficiency since it was assumed that an app needing concurrency would create multiple threads rather than spawn processes.

      CreateProcess was a heavy, slow operation (at least back then, I don't know about recent Windows kernels); I've verified that myself. Windows also lacked a native fork() call for fast process cloning. It was much more efficient to keep a thread pool around inside an app to handle asynchronous inputs than to spawn processes for them.

    9. Re:I'm All For Getting Rid Of Threads, But... by jythie · · Score: 1

      The entire point of threads is to share everything ^_~

      If you want limited sharing you can still make use of thread design by using fork or clone to only share the things you want to.

    10. Re:I'm All For Getting Rid Of Threads, But... by Tablizer · · Score: 1

      I'm all for getting rid of threads, but what are you going to replace them with?

      RDBMS-like communication (with A.C.I.D. transactions). Tried and Trued.

    11. Re:I'm All For Getting Rid Of Threads, But... by Cheesey · · Score: 2, Interesting

      It's very unfashionable, but the Ada language has threads (tasks) as a first-order part of the language, so you don't need a specific class or library in order to use them. The things you need to use threads safely, like protected objects, are also part of the language. That means it is very easy to write correct multithreaded code in Ada. You won't be missing a mutex unlock command, and you won't be accessing something owned by another thread: the compiler won't let you.

      Threads are one thing that Ada does really well. I don't know of any other language in the ALGOL family that matches it. Certainly C/C++/Java are far behind.

      --
      >north
      You're an immobile computer, remember?
    12. Re:I'm All For Getting Rid Of Threads, But... by Anonymous Coward · · Score: 0

      Pfffft. OOP usually sucks. Enough of the hype. It is good for a few things, but some overclaim it.

    13. Re:I'm All For Getting Rid Of Threads, But... by hardburn · · Score: 1

      There are a lot of places where you want a halfway solution, though. For instance, languages embedded in web servers that normally do automatic memory management (like mod_perl), it's difficult to predict memory usage when COW kicks in for a fork model. At the same time, you want separate processes to maintain encapsulation.

      Solutions are to not use garbage collected languages (except we usually have plenty of other reasons to use them), throw on a whole lot of RAM (which can get expensive for a whole cluster), or tightly monitor the processes (annoying, but works pretty well most of the time).

      --
      Not a typewriter
    14. Re:I'm All For Getting Rid Of Threads, But... by abigor · · Score: 1

      The entire point of threads is to share everything ^_~ Agreed, which is why it's not a one-size-fits-all multiprocessing solution. Unfortunately, most people think it is, and that it's the only option.

      In fact, sharing everything is generally unsuitable except in some cases - what you really want to do is share certain objects.
    15. Re:I'm All For Getting Rid Of Threads, But... by SanityInAnarchy · · Score: 1

      Well, I don't know of anything else you'd replace it with. (I consider processes to be a higher level of abstraction.)

      What else were you suggesting -- just ignore the issue? The implicit assumption here is that we must write programs which can scale to multiple cores, because single cores are running into the limitations of physics.

      --
      Don't thank God, thank a doctor!
    16. Re:I'm All For Getting Rid Of Threads, But... by StarvingSE · · Score: 1

      It all depends on the application. If response time is important, then threads are the way to go. If ease of programming and portability is important, use fork.

      I did a project in a distributed programming class where we wrote two versions of a simple web server in c++ on solaris, one using a "one process per connection" paradigm, and the other using "one thread per connection." The threaded version was obviously much faster. Of course, you could always just create a process pool and eat the initial startup cost in favor of faster response times.

      Its all about how you need to use it. Threads are not necessarily better than true multiple processes, and vice versa. They are all tools in the programmer's toolbox, just choose wisely.

      --
      I got nothin'
    17. Re:I'm All For Getting Rid Of Threads, But... by Foolhardy · · Score: 2, Informative

      Just to clarify, NtCreateProcess, the kernel syscall to create a process, is much lighter than Win32's CreateProcess function. NtCreateProcess doesn't even start any threads in the new process or load dependent libraries. CreateProcess includes out of process calls to register with CSRSS, an application compatibility database lookup since XP (so slow that there's a special option on WS2003 to turn it off), tons of registry reads, among other things.

      NtCreateProcess even supports COW fork, by specifying a NULL image to load-- it's the Win32 libraries that aren't designed to support forking. POSIX^W SFU^W SUA processes are much lighter than Win32's and can use the kernel's fork support.

    18. Re:I'm All For Getting Rid Of Threads, But... by jythie · · Score: 1

      Agreed.

      It's actually kind fun playing with the lower level clone calls to get just the solution one needs for a situation.

      Though moving forward I am using threads less and less and fork/anon mmap more and more unless something is really lightweight (and encapsulated within a single class object)

    19. Re:I'm All For Getting Rid Of Threads, But... by DragonWriter · · Score: 1

      I'm all for getting rid of threads, but what are you going to replace them with? Traditional functional languages may be the most obvious solution, but they're also among the most impractical of solutions.


      "Traditional functional languages" are not a replacement for threads; functional languages may or may feature concurrency and if they do they can feature just about any concurrency model. A concurrency model with shared-nothing processes communicating through "mailboxes" (the Actor model) is a frequently recommended replacement, and some of the languages that embrace that as their concurrency model are functional languages (e.g., Erlang and Oz), but some are not (e.g. E, Io.) One advantage of the actor model is that it naturally extends to non-local distributed computing as well as local concurrency.
    20. Re:I'm All For Getting Rid Of Threads, But... by ralphdaugherty · · Score: 1

      I'm all for getting rid of threads, but what are you going to replace them with?

            Separate jobs communicating with message queues in some case. Communications should be isolated out to a separate job so the OS is coordinating multi-tasking, not the program.

            Some things I understand is threaded for responsiveness, such as monitoring for keystrokes while painting screens, but an interrupt mechanism would do it I think, where you get the responsiveness but no contention on data to update.

            In general, thread() safe programming replaced by multiple lightweight OS jobs communicating.

        rd

    21. Re:I'm All For Getting Rid Of Threads, But... by jgrahn · · Score: 1

      I'm all for getting rid of threads, but what are you going to replace them with? Traditional functional languages may be the most obvious solution, but they're also among the most impractical of solutions. Is there anything else out there that can replace threading needs, without throwing out the book on programming? It seems like what we need hasn't been invented yet.

      Depends on what your "threading needs" are. The Unix select(2) call takes care of one common use case, and has existed for 25 years.

  9. Just Add Abstractions by xp · · Score: 1

    Threads are fine if you have clean abstractions around them. Sort of like gotos are fine when abstracted out as for/while/do/etc.

    --
    Feed Weed: Feed your web addiction

  10. I disagree with both this guy AND Dijkstra by halivar · · Score: 4, Interesting

    Goto's and global variables are not inherently wrong or evil. They are tools. Granted, they are tools that, if misused, will wreak havoc on your code's stability and maintainability. The same could be said, however, for pointers. Threads are dangerous, and require special care. This is not a reason to avoid them; it is only a reason to be incredibly careful with them.

    Use the best tool for the job, regardless of whether your CS professors demonized it or not.

    1. Re:I disagree with both this guy AND Dijkstra by Nerdfest · · Score: 1

      Exactly. I'm sure we've all seen well written multi-threaded code (although admittedly not frequently) where each thread accomplished a set task and isolated the complexity of the task. In general, I think code that abuses pointers or inheritance is more difficult to to maintain.

    2. Re:I disagree with both this guy AND Dijkstra by RManning · · Score: 0

      Use the best tool for the job, regardless of whether your CS professors demonized it or not.

      I've been a programmer for a number of years now and the more experience I have the more I realize that certain constructs or patterns are inherently bad and wrong. I think what's important to remember is that the decisions you make as to how you write something has as much or more to do with long-term maintainability and extensibility as it has to do with solving a particular problem in the best way. It's a hard lesson to learn, but in my experience it's true.

      So, not to defend CS professors (a lot of them don't need defending or deserve it), but don't discount the "thinking" part of programming. Sometimes using a blunt tool works great, but overall it's best to shoot for something higher.

    3. Re:I disagree with both this guy AND Dijkstra by Hoplite3 · · Score: 1

      I completely agree. If you want to take the guard off your skill-saw to save time doing a job, that's your business. You might finish faster, you might cut your foot off, but it's your call.

      I certainly abuse global variables in my code, but I write my code for me to solve my problems. The loss of encapsulation that results isn't so extreme when there's one author, and the gain in flexibility is pretty steep.

      However, I do think that avoiding nastiness is important, especially as the size of the group coding grows. To return to the skill-saw analogy, if you cut off your own foot, that's the risk you took. If you cut off your colleague's foot, he'll be pissed :)

      --
      Use the Firehose to mod down Second Life stories!
    4. Re:I disagree with both this guy AND Dijkstra by Paralizer · · Score: 1

      Yes, but there appears to be a trend that is moving away from lower level coding, where there is a need to be careful and you do need to take your time to find an eliminate bugs; elegant and efficient programming does not seem to be as great a concern as I think it should be. If computers have more RAM then let garbage collection take care of your memory management woes; if CPU's are getting faster then maybe we should use inherently slower, but more programmer friendly, techniques to deal with threading.

      In business applications this approach works fine -- you get a quick solution that fixes your immediate problem. When it comes time to deploying a solution to end-users I strongly disagree with taking the easy path -- just because your end-user has more system resources than they did 3 years ago doesn't mean you can write a slower application. Threads work. Handling memory yourself works. Maybe there are better techniques that will emerge, but those techniques should not, and can not, degrade the performance we can achieve with current methods.

    5. Re:I disagree with both this guy AND Dijkstra by halivar · · Score: 1

      don't discount the "thinking" part of programming. Sometimes using a blunt tool works great, but overall it's best to shoot for something higher.
      If someone is using a global variable, goto, or thread model as a "blunt tool" without concern for elegance, readability and robustness, they have already validated all the dire warnings against using these constructs. I use them only where, after rigorous examination, I have decided I can use them without sacrificing the three aforementioned design goals.
    6. Re:I disagree with both this guy AND Dijkstra by Anonymous Coward · · Score: 0

      Threads are a tool in the same way that nitroglycerin is.

    7. Re:I disagree with both this guy AND Dijkstra by nacturation · · Score: 1

      "Gotos aren't damnable to begin with. If you aren't smart enough to distinguish what's bad about some gotos from all gotos, goto hell."
              -- Erik Naggum

      --
      Want to improve your Karma? Instead of "Post Anonymously", try the "Post Humously" option.
    8. Re:I disagree with both this guy AND Dijkstra by Chandon+Seldon · · Score: 2, Interesting

      If you don't think that we should be using hardware advances to make things easier on programmers, then why do you use compilers? Compared to hand-tuned machine code specific to each target processor, the stuff that comes out of a C compiler is slower by a factor of 2 to 10 at least. Other languages even more so.

      The fact of the matter is that high level tools are almost always the right choice, and the standard rules of optimization apply:

      Rules of Optimization:
      1. Don't do it.
      2. (experts only) Don't do it yet.

      With concurrent code that's just as true as it ever was. If you can use an abstraction that makes thing easier to understand, you'll get the project finished on time and stable. On time and stable trumps 3% faster with deadlocks a year late *every single time*.

      --
      -- The act of censorship is always worse than whatever is being censored. Always.
    9. Re:I disagree with both this guy AND Dijkstra by sjames · · Score: 1

      One should not just toss out CS and certainly not thinking, but never is a very strong statement.

      A beginning programmer, particularly one who was exposed to goto laden BASIC should NEVER use goto. They don't have the experiance and haven't developed enough good taste to understand when it could be OK.

      Later, after becoming more experianced, it may be time to revisit that and other cut and dried rules. I have seen well used gotos that made the code easier to follow and maintain and I have seen code that because of goto should just be shredded and rewritten.

    10. Re:I disagree with both this guy AND Dijkstra by decoutt · · Score: 1

      See Donald Knuth's "Structured Programming with GOTO Statements" (Computing Surveys, Vol 6 Nr. 4 December 1974).

      PDF : http://pplab.snu.ac.kr/courses/adv_pl05/papers/p261-knuth.pdf

      --
      .sig
  11. Not really news by AKAImBatman · · Score: 5, Insightful

    Threads have been considered a "bad idea" by the CompSci profession for a little while now. So there is definitely nothing new about the author's statements. That being said, there is a fundamental difference between Dijkstra's paper 40 years ago and this summary: Dijkstra started his paper by holding up examples of better practices. Only after establishing their existence did he go on to suggest that the GOTO keyword was "too primitive" to be of practical use in software development.

    The author of this "article" (and I use the term loosely) doesn't really present such options. He hand waves a few work-in-progress solutions at the end, compares threads to GOTO statements, then asks the readers to fill in the (rather sizable) blanks.

    Long story short, it's a good topic of discussion, but the comparison to Dijkstra's famous paper is just an advertising point. Nothing more, nothing less.

    1. Re:Not really news by Threni · · Score: 1

      > The author of this "article" (and I use the term loosely) doesn't really present such options. He hand waves a few work-in-progress
      > solutions at the end...
      > ...Before you adopt Silverlight, read the WHATWG specs [whatwg.org]. Article coming soon...

      I like a man who appreciates irony...

    2. Re:Not really news by Paradise+Pete · · Score: 1
      Dijkstra started his paper by holding up examples of better practices.

      No he didn't. In the opening paragraph he says use of the goto statement has "disastrous effects" and that it "should be abolished from all 'higher level' programming languages." It's not until halfway through the letter that he gets around to an example of a better practice.

  12. If you can't stand the heat by DrSkwid · · Score: 1

    Get a better programming language.
    And if don't like the taste of that one (what? Dennis Ritchie & Brian Kernighan not good enough for you!) there are other CSP languages available (what? Sir Charles Hoare not good enough for you!)

    Seriously, this problem has been solved for 30 years.

    --
    There are places where the networks are not touching,and there are places where they are-Boeing's Lori Gunter
    1. Re:If you can't stand the heat by Anonymous Coward · · Score: 0
      STFU, snobby fanboi.

      I used limbo, it's a joke. It doesn't fix any of the problems with java or ada. You're just learning yet another toy language with a funny syntax. Saturated with the prejudices and idiosyncrasies of its authors.

      Typical case of elite stupidity.

    2. Re:If you can't stand the heat by DrSkwid · · Score: 1

      That's the problem with being a member of the elite, I guess.
      Still, I suppose the CSP features of Ken Thompson C are beyond you as well. You'll have to stick to a single thread.

      --
      There are places where the networks are not touching,and there are places where they are-Boeing's Lori Gunter
    3. Re:If you can't stand the heat by Foolhardy · · Score: 1

      Get a better programming language.
      I do agree that this problem has been solved for a long time, but I think it's done better with modern functional languages. I'm looking at Limbo's features, and it looks like GHC does all of those things, and more, better. Take the multithreaded "Program 2" example from that Limbo example page, implemented in Haskell:

      module Timer where
      import System.Environment
      import Control.Concurrent
      import Control.Concurrent.Chan

      main = do {
      putStrLn "Command Line Parameters";
      sync <- newChan;
      args <- getArgs;
      forkIO $ timer sync $ length args;
      sequence_ $ zipWith (zipf sync) [1..] args;
      } where zipf sync n s = (readChan sync) >> (putStrLn $ (show n) ++ ": " ++ s)

      timer :: Chan Int -> Int -> IO ()
      timer sync n = mapM_ (\n -> (threadDelay $ 1000000) >> (writeChan sync n)) [1..n]
      Haskell's not even a sequential language by nature. Standard Haskell code is a series of side-effect free, deterministic expressions that are executed on demand, which makes execution timing issues (even across CPUs) much less relevant (and invisible to data processing in the program).
    4. Re:If you can't stand the heat by DrSkwid · · Score: 1

      Yep, I'd agree pretty much with that, CSP style programming is an ideal match for multi-threaded application development. Not having to think too much about synchronization and locking and mutexes is a boon.

      --
      There are places where the networks are not touching,and there are places where they are-Boeing's Lori Gunter
  13. I wonder how long... by Thalagyrt · · Score: 1

    I wonder how long this trend in this discussion will continue of most every post being its own post as opposed to replying to a previous post.

    --
    Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo!
    1. Re:I wonder how long... by trolltalk.com · · Score: 1

      I wonder how long this trend in this discussion will continue of most every post being its own post as opposed to replying to a previous post.

      ... because, as the article says, "threads are bad." But I'll do threads, 'cuz I'm evil :-)

  14. Don't see any serious problems by markov_chain · · Score: 1

    The motivation for widespread parallel programming seems to be that there is this upcoming glut of multicore PC chips that will get wasted if we all don't start writing concurrent programs. But is that really true? Most programs don't get any speedup from parallelization; at best a UI/core split helps the responsiveness of an app. Chances are a SMP OS would be able to reap most of the available gain.

    --
    Tsunami -- You can't bring a good wave down!
    1. Re:Don't see any serious problems by ezzzD55J · · Score: 1
      Chances are a SMP OS would be able to reap most of the available gain.

      Doing what? I'd hope any OS (SMP or otherwise) doesn't significantly use the CPU itself. For an SMP OS to have something to gain by multicore, it has to come from a parallelizable workload, hence threads. (Unless you have enough runnable processes, but that often isn't so.)

      Unless you meant more responsiveness / lower interrupt latency or something like that in an OS, which is fair enough, but not exactly using multicore to its fullest.

    2. Re:Don't see any serious problems by TheBig1 · · Score: 1

      Unless you have enough runnable processes, but that often isn't so.

      I regularly have 10+ applications open at once, and that is not counting background processes.

      From my experience, I see family / office workers, who would not be considered very technical, tending to have multiple applications open at once - web browser, music player, email, office suite, etc. Add in an AV scanner and background processes, and I can see that you can easily take advantage of up to 8 cores.

      Now, I admit that these applications would not keep all 8 cores at 100%, but then again most users don't max out even a single processor that often. I would argue that many cases which I have seen (again, just my experience) where people are complaining about slow computers are directly related to the responsiveness / latency. I don't really notice if something take 30 seconds vs. 50, but I easily notice if my mouse pointer is lagging by even a few milliseconds. If adding on a couple extra cores can reduce things like that, I am all for it!

      Cheers

    3. Re:Don't see any serious problems by Tablizer · · Score: 1

      The motivation for widespread parallel programming seems to be that there is this upcoming glut of multicore PC chips that will get wasted if we all don't start writing concurrent programs. But is that really true? Most programs don't get any speedup from parallelization;

      The disk is often the bottleneck in my experience. Multi-disk systems to split the load (based on server technology) is the next PC wave would be my guess.

    4. Re:Don't see any serious problems by DragonWriter · · Score: 1

      The motivation for widespread parallel programming seems to be that there is this upcoming glut of multicore PC chips that will get wasted if we all don't start writing concurrent programs.


      Another reason is distributed programming. Often (as is the case with the Actor model) the same solutions that address problems with traditional threading on one machine (and thus make local parallel programs that can take advantage of multicore CPUs cleaner to develop) also apply directly to distributed programming across many machines.

      But, in any case, I think its pretty clear that multicore chips are going to become more common and the number of cores on the average machine are going to be increasing for a while, so there certainly will be some increase in the applications for local parallelism. How far that will go is hard to say.
    5. Re:Don't see any serious problems by NotZed · · Score: 1

      Actually - yes it is true. Almost every application would benefit from multi-threading to some extent.

      You dismiss ui interactivity like it isn't important - but it is. But that isn't 'at best' at all. Also note that many gui toolkits have work-arounds so you don't need to use threads (i.e. io, timer events, etc) - but all these are are just threading anyway, and often harder to use and harder to debug than 'real' threads.

      Lets look at a few common applications and see how threading helps them:

      1. graphics applications. Using 4 cores to perform your blur filter is going to be faster than 1, and blocking the ui while you're doing it (or doing it in chunks and polling for new events is even slower).
      1.1 viewing pictures. Threads can be used to easily pre-fetch and decode pictures before they are shown.
      2. playing music. using a thread to play the music with a gui controller running separately will be easier to write and debug than using timout events and non-blocking i/o. Multiply the issue if you're playing and mixing multiple audio streams at once. Also note an os thread context switch is often going to be more efficient than a manual context switch (i.e. we have new data, lets re-load all of our state from where we were before, do the work, save our state manually because we've run out of work to do, return to the event loop, vs read data, process (our state is already 'here'), wait for more data) - so it might even use less total cpu time.
      3. i/o bound applications. Using threads you can pre-fetch data in ways the operating system cannot (it will only pre-fetch linearly), and thus process with reduced latency and potentially reduced overall running time. Again you can do it with select/poll but often using a thread will be simpler to code and debug (a simple read loop vs register event, listen for event, process event, repeat).
      4. business applications. threads can be pre-calculating results as you're using the ui, so you can improve the workflow of the user - e.g. so they don't have to hit a calculate button and wait for results. And many hard-to-calculate results can be calculated in parallel so you get your results faster.
      5. online transaction processing. well processes probably work here as well as threads - but at some point things need to go through some thread-like mechanism. e.g. database access or filesystem access 'threaded' by the kernel.
      6. web browsers. threads are essential here so your flash based adverts don't slow the rest of the application down too much. Again using threads is easier than polling.

      In almost all non-trivial interactive applications threading can improve the user experience and reduce overall running time, while at the same time simplifying coding and debug (even on a single-cpu machine). It will also accelerate any parallel algorithm (on suitable hardware) and possibly simplify its code and debug as well.

      Threads are not perfect but they are a practical solution to a real problem - how to get improved performance using modern hardware which is only increasing in its number of cores. So the opportunities in which threads increase performance will only increase. And auto-parellising languages/compilers will always be years away. There are real practical reasons java emphasises thread's so much - remember it was invented by a hardware manufacturer who knew where cpu's were going.

      All interactive gui applications that do non-trivial work have to use threads - but they might not be using pthreads. Registering an event handler and callback and processing it, or doing a little bit of work at a time in an 'idle handler' is just a crude form of threading - one that has no debugger support and can be a total nightmare to debug. If there were 3 processing loops - a timeout, an idle handler (for say applying biz-wang filter on photoshop a few rows at a time), and handling user input, which do you think would be easier to debug. Using threads where you can view each thread's stack exactly where it is at a given point in time, or looking at some internal gui toolkit 'events pending' list which you may not even be able to see from the debugger in any form other than hex codes?

      --
      _ // `Thinking is an exercise to which all too few brains
      \\/ are accustomed' - First Lensman
  15. Hmm by LizardKing · · Score: 2, Interesting

    The problem is not threads per se, but the way they are generally used in programming languages like C and C++. Although const correctness is understood by some C++ programmers, they appear to be a minority if I judge by the code I regularly review. There is also memory management which is a much bigger issue in threaded C/C++ applications than in applications written in Java. The Java library provides good examples of immutable classes, most prominently the String class, that remove a number of problems often encountered with their mutable cousins like std::string. Unlike std::string, I don't have to remember to make it immutable by constifying it or wrapping it. The presence of immutable classes, and the more adequate coverage given them along with threading in Java textbooks means that I disagree with the articles' author who lumps Java threads in with pthreads as a bad thing. What we need is more coverage of threading issues and how to alleviate them in intermediate level C/C++ textbooks, because despite the fact that threading is not built into those languages or their standard libraries, concurrency has become too important to ignore once you go beyond the basics.

    1. Re:Hmm by Max+Threshold · · Score: 2, Interesting

      Yeah. The main problem I've seen is that many developers apparently don't understand event-driven programming at all, so they end up creating dozens of threads to poll for various conditions, and then usually fail to come up with a thread-safe way of coordinating the whole mess. Threads aren't the problem; applications will always use threads, even if it's not explicit. Incompetent developers are the problem.

    2. Re:Hmm by BotnetZombie · · Score: 1

      Exactly. I dunno why so many people look at this as rocket science. All you really need is to put something immutable on a queue. Whatever takes it from there creates some immutable output that gets put somewhere else. Rinse and repeat.

    3. Re:Hmm by owlstead · · Score: 1

      Exactly. We need better a bigger focus on multi-threading within the current languages, if still possible.

      I've just seen a very nice presentation on how null pointer exceptions can be avoided using annotations in the Java language. The same presentation also showed how to annotate variables to be immutable: changes to the variable would be picked up by the compiler.

      That said, with the possible exception of Java arrays, it's pretty easy to make variables immutable (basic types are referenced by value, collections can easily be made immutable as well). Add to that the many threading classes and the synchronized method and you've got a very nice language to handle parallelism, even though it doesn't do multi-threading automatically. That said, I wouldn't be surprised if that would be added to the JVM in some long distance future.

      Problem with Java is the way that Beans have become so important, at least in the EE framework. These are the devil if you are a proponent of immutability and should be handled very carefully.

      Anyway: link to the presentation on @NonNull and @Immutable:

      http://www.nljug.org/pages/events/content/jspring_2008/sessions/00042/

    4. Re:Hmm by LizardKing · · Score: 1

      Problem with Java is the way that Beans have become so important, at least in the EE framework. These are the devil if you are a proponent of immutability and should be handled very carefully.

  16. Making a parrallel with Edsger Dijkstra's article? by Lazar+Dobrescu · · Score: 2, Insightful

    You know the big difference between TFA and Edsger Dijkstra's paper?

    The second one made an argument, showed alternatives that were at least summarili demonstrated to be better and used reasoning.

    The first one just says "Edsger Dijkstra's paper said goto was harmful and he ended up being right, thus if I say threads are harmful, I'm also right. Oh and here are some threading libraries I've found in a quick google search, they might be better."

  17. processes by mkcmkc · · Score: 3, Interesting

    Well, for starters, there's processes, which were invented in the 1960s. These may not handle every case, but in my experience they'd cover 95+%...

    --
    "Not an actor, but he plays one on TV."
    1. Re:processes by kalirion · · Score: 0

      I'd love to see a web server spawn a separate process for every page access.

    2. Re:processes by Nutria · · Score: 2, Insightful
      I'd love to see a web server spawn a separate process for every page access.

      Apache 1.x is not multi-threaded.

      --
      "I don't know, therefore Aliens" Wafflebox1
    3. Re:processes by VGPowerlord · · Score: 1

      I'd love to see a web server spawn a separate process for every page access.

      Apache 1.x is not multi-threaded.

      In addition, Apache 2.0.x and 2.2.x default to mpm_prefork on *nix.

      However, Apache reuses its child processes for more than one page load. In addition, HTTP/1.1 allows you to keep a connection open to request multiple pages from it before closing the connction.
      --
      GLaDOS for President 2016! "Well here we are again. It's always such a pleasure." -- GLaDOS, 2011
    4. Re:processes by xiox · · Score: 1

      I'd love to see a web server spawn a separate process for every page access. If you look at Linux (and other unixes) you'd find that forking processes is a very cheap operation. This is unlike Windows where it is very expensive. Using processes in Unix is a sensible idea for many programs and works well (see Apache, many MTAs...).
    5. Re:processes by smallfries · · Score: 1

      These are not the processes you are looking for...

      He is referring to processes as a language mechanism for encapsulating state and communication. Not as in O/S level encapsulation of state.

      Language-based processes are very light-weight. Look at Erlang, any of the Occam spin-offs or any of the other theoretical...

      hmm, 1960s? That sounds very early for CCS or CSP. Oh dear, I think you're right, he is talking about forking processes for each unit of concurrency. Shoot him, shoot him now

      --
      Slashdot: where don knuth is an idiot because he cant grasp the awesome power of php
    6. Re:processes by abigor · · Score: 1

      Apache2 uses processes or threads, and I believe processes are still the default (not sure though, I'm sure somebody will correct me).

      There are some gotchas when using Apache threads - read here: http://httpd.apache.org/docs/2.0/developer/thread_safety.html

    7. Re:processes by Metasquares · · Score: 2, Insightful

      That's what select() is for.

    8. Re:processes by 2short · · Score: 1


      Mine does.

      Or rather, each hit is handed off to a separate process that handles it, but assuming there are no errors, that process will be reused for a future hit. Thus, we can still cache stuff and skip startup costs most of the time, but still use code that may not be thread safe. I entirely agree with the articles author; third party code that claims to be thread safe often isn't. With process isolation, I don't have to care.

      Note that I'm running fairly low volume but extremely processor intensive web apps; not high numbers of hits to simple html pages. YMMV.

    9. Re:processes by iangoldby · · Score: 1

      I'd love to see a web server spawn a separate process for every page access.
      One thread/process per client is an incredibly inefficient way of managing connections on a server, even on Windows. The only thing in its favour is that you don't have to think about the code that you are writing because the connection context is embedded in the thread context, which is handled for you by the OS.

      I don't know about writing servers on UNIX, but I do know that you can write a far more efficient server using Windows' overlapped I/O. No threads in sight and all I/O is asynchronous. If that isn't efficient enough for you then you can read up on Microsoft's I/O completion ports. Even if you want to utilise multiple processors, Microsoft's recommendation now is to limit the number of (active) threads to the number of processor cores.
    10. Re:processes by sjames · · Score: 1

      I don't know about writing servers on UNIX, but I do know that you can write a far more efficient server using Windows' overlapped I/O. No threads in sight and all I/O is asynchronous. If that isn't efficient enough for you then you can read up on Microsoft's I/O completion ports. Even if you want to utilise multiple processors, Microsoft's recommendation now is to limit the number of (active) threads to the number of processor cores.

      It's all there and more if you want it in Linux though some of the API is a bit different. A common one for handling many clients asynchronously is to set a signal on file and socket handlers then either queue it up in a signal handler or block the signal and loop on sigwaitinfo.

      Depending on what you're doing, you can even open a file and splice it onto the socket handle to have the OS send the file back for you (skipping the need for intermediate DMA buffers) after sending a header if necessary.

      Those features are not used frequently. They are more efficient and faster but at the cost of complexity. In most situations you're better off with clean, easily debugged, and more obviously correct code. In Linux, the performance hit from the simple approach isn't so bad. The rest is there because it's interesting to work on (frankly) and for that 1% or so cases where it can actually be justified.

    11. Re:processes by tepples · · Score: 1

      That's what select() is for. How well does a single-process, single-thread server whose main loop involves a select() take advantage of multiple cores? Or did I misunderstand your terse comment?
    12. Re:processes by perlchild · · Score: 1

      I'd say that this discussion is there, and the title of the article is more interesting than the article itself, mostly because all those lovely, non-cross platform options, aren't wrapped at the language level... And having the cross-platform, generic, unoptimized "threads" abstraction, is harmful, just because nobody bothers to learn the optimal, platform specific ones(or better yet, write a platform agnostic, optimizing solution) where the programmer(they are lazy and require a whip to read any documentation beyond 10 pages, in my experience) doesn't have the choice to NOT do the right thing.

      I'm surprised concurrent/ml and coroutines haven't come up into the discussion yet, as especially, coroutines might be a different, better approach.

    13. Re:processes by GileadGreene · · Score: 1

      You mean like Yaws? To quote from their website: "...one Erlang light weight process is used to handle each client...". Of course, they also say: "...performance comes from the underlying Erlang system and its ability to handle concurrent processes in an efficient way...". Using "processes" doesn't necessarily mean using heavyweight OS processes. It mostly means avoiding shared state, which is the root of the problems with threads. Languages like occam and Erlang provide lightweight processes with extremely fast context switching and quick interprocess communication.

    14. Re:processes by GileadGreene · · Score: 1

      hmm, 1960s? That sounds very early for CCS or CSP.
      Indeed. Hoare's original CSP paper dates from 1978. IIRC Milner's first published work on CCS was around 1980. He'd previously done some other work on process-based concurrency, but I think even that goes back only to the early 70's.
    15. Re:processes by dkf · · Score: 1

      Those features are not used frequently. They are more efficient and faster but at the cost of complexity. In most situations you're better off with clean, easily debugged, and more obviously correct code. In Linux, the performance hit from the simple approach isn't so bad. The rest is there because it's interesting to work on (frankly) and for that 1% or so cases where it can actually be justified. While I'm not 100% sure what you're talking about there, I'll assume it's asynch IO. The key to it is that the default API for it on both Unix and Windows is a bit low-level for most people; it really requires a higher-level abstraction on top so that you can work in terms of event-driven callbacks. At that point, asynch IO becomes much simpler since you can think in terms of "when there's data available, process it" which is (to my mind) easier than having to have loads of threads stamping on each others' toes.

      The only real benefit of threads comes when you are CPU-bound, and when you can avoid locking lots of memory through intelligent algorithms. Get that right and you can get a lot of speedup from getting multiple cores going on the same problem. Alas, it remains a research-level problem for many tasks...
      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    16. Re:processes by smallfries · · Score: 1

      Much like witty retorts in bars that you come up with the next day, I now realise that the final part of my comment should have read "kill him now, kill kill, kill -9" ... ah, life's too short, at least on slashdot I can post that next time the discussion comes around :)

      --
      Slashdot: where don knuth is an idiot because he cant grasp the awesome power of php
    17. Re:processes by sjames · · Score: 1

      Mostly, I was talking about event notification. aio is also available both as POSIX and a Linux specific variation. There is a good bit of effort in the standard libraries to make sure they use the more advanced low-level interfaces wherever they are available.

      AIO and threading are closely related. Where aio isn't supported by the OS, it can be credibly emulated using threads in the libraries.

      Personally, I find that in many cases threads or forks are less of a problem than using aio. The thread context is a useful container for an object's state.

      For example, a web-like server. http may be called stateless but it's really a series of small standalone stateful requests. The dispatcher easily knows when a client wants to make a request because the associated socket becomes ready for read. This is a convieniant point to post it to a work queue or to explicitly assign it to a worker thread. The thread can then read the request, take any of a number of steps to fulfill the request involving one or more files and/or handing off to an external program or running an internal interpreter. The advantage is that the worker-thread function can be written easily as as if it was a well scoped function in a single threaded program. In fact, it could even BE a well scoped function(s) in a program that once WAS single threaded.

      By contrast, aio completely breaks up the program flow and may require an entirely different approach to the whole problem. While it is to a degree just a matter of taste, aio seems to me to invite poor scoping and fuzzball data structures.

      That is why there has been a good bit of effort in the Linux kernel to provide efficient mechanisms for event notification, polling, and waiting (in several flavors) as well as a fast atomic primitive (futex) usable in multi-threaded and multi-process apps. In addition, there has been considerable work on making the scheduler efficient and fast with large numbers of threads and proccesses.

    18. Re:processes by Anonymous Coward · · Score: 0

      That's what select() is for. How well does a single-process, single-thread server whose main loop involves a select() take advantage of multiple cores? Or did I misunderstand your terse comment? Very well, if you spawn multiple instances of this server. (With the appropriate request distribution scheme of course.)
    19. Re:processes by tepples · · Score: 1

      Once you're spawning multiple server processes, you still need to lock anything that a server might update. Processes make it slightly easier than threads because the process's internal memory doesn't need to be locked as often, but any time you execute a POST or log a GET, you still have an update.

  18. Alternatives by Dancindan84 · · Score: 1

    Lots of things in programming have the -potential- to be bad. Pointers and references, constructors and destructors can be horrible if not handled properly. So an alternative to manually handling those elements came about: automatic garbage collection to free up unused memory. The problem is, garbage collection itself can be a pig.

    The same goes for threading. If not handled properly it can be a nightmare, but in a time where processors are growing cores faster than rabbits can breed it makes the most sense to take advantage of that with parallel programming. Whenever there's options that have pros and cons, the best alternative is chosen based on them.

    If you have a good programmer that understands threading, an application that has a lot of concurrent connections and/or multiple, concurrent CPU intensive tasks, and a server that can take advantage multi-threading it makes the most sense to go that route.

    If you have a rinky-dink, single user application and a developer that has trouble using negatives in conditional statements, by all means don't use threading.

    Just don't claim that threading is unequivocally always the wrong option.

    --
    "Always forgive your enemies; nothing annoys them so much." - Oscar Wilde
  19. Re:How about "C++ threads considered harmful"? by Anonymous Coward · · Score: 0

    Erlang is multi-process, not multi-thread. A particular runtime may use threads, but that's certainly not the logical model of the language, just an implementation detail.

  20. rocks considered harmful by nategoose · · Score: 1

    Threads are good and bad. Same with Goto. I use both, but avoid using goto when it's not needed and avoid using threads when they don't make sense. Most programming languages that people use directly have several branching statements that hide the Gotos to make them less likely to be harmful when dealing with common types of their uses. The erlang language was created just to deal with threads, and makes them a lot more difficult to hurt yourself with.

  21. Re:How about "C++ threads considered harmful"? by LizardKing · · Score: 2, Informative

    The articles' author explicitly mentions Erlang as a potential solution to threading issues in other languages. In fact he's mainly concerned about POSIX pthreads, Boost threads, Java threads (and presumably Windows low level thread libraries). As I point out in another post below, I disagree with him lumping Java threads in with those used in most C/C++ libraries, as threading support is integrated into the language along with increasingly sophisticated locking support in the library which can be used if the simple object lock is insufficient. In my experience, most data shared across threads is immutable (read only), and the Java libraries encourage use of immutable types such as String. Once you appreciate the value of immutable types, then they can be used just as easily in C++ (with C it's a little harder). Writable shared data can be cleanly hidden behind a decent interface, with the locking within the getters and setters, but again, this approach is applicable in C++ as well as Java.

  22. Slowaris caused threading by Russ+Nelson · · Score: 1, Troll

    Slowaris is behind threading. Because it was so slow to create new processes, the only way they could compete with Linux (which forks very quickly) was to create threading. Threading *is* faster than forking, but it also creates HUGE synchronization problems. You can overcome these problems, at the cost of more complicated, more fragile programs that take more time to write and more time to get right.

    Linux doesn't need threading.

    --
    Don't piss off The Angry Economist
    1. Re:Slowaris caused threading by LizardKing · · Score: 3, Insightful

      Complete crap. Threads solve a number of programming problems much more elegantly than forked processes and sharing data through some IPC mechanisms. Anecdote time: a stock price system I worked on. The first generation used separate processes for a single writer and a large number of readers, with shared memory for interprocess communication. This was switched to a threaded implementation for the second generation, which was faster, even though it was using the old LinuxThreads implementation, and more easily maintained as the pthreads API is much richer than IPC ones.

    2. Re:Slowaris caused threading by ceoyoyo · · Score: 1

      You can overcome synchronization problems with threads in EXACTLY the same way you do it with processes.

      The problem seems to be that some of the more popular languages don't enforce that behaviour. In other words, the programmer has to be (gasp) competent!

    3. Re:Slowaris caused threading by owlstead · · Score: 1

      Yeah, even better, use complete different VM's. Of course, if you want any communication between those you need to use sockets or files, including authentication etc.

      With different processes you have the same problem as between two different VM's, although you may make use of non-networked resources such as pipes and local files.

      The big advantage of threads is that they run in the same memory space. If you use managed code within the threads, this means that the threads cannot access the other thread's memory unless you allow them to do so.

      One of the best known applications on Linux is of course Apache. Guess which way they went? Yeah.

    4. Re:Slowaris caused threading by dkf · · Score: 1

      Threads solve a number of programming problems much more elegantly than forked processes and sharing data through some IPC mechanisms. Anecdote time: a stock price system I worked on. The first generation used separate processes for a single writer and a large number of readers, with shared memory for interprocess communication. Out of curiosity, what other things were the readers and writers doing? Was the overall system IO-bound or CPU-bound? Threads only help for CPU-bound problems; for IO-bound stuff, you're better off using asynchronous processing.
      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    5. Re:Slowaris caused threading by Russ+Nelson · · Score: 1

      Uh-huh, and how are stock prices doing now? They're in the shitter and I Blame You and your threads.

      --
      Don't piss off The Angry Economist
    6. Re:Slowaris caused threading by Russ+Nelson · · Score: 1

      The difference being that a bug in one thread affects every other thread, whereas a bug in one program is a bug in one program, and can be debugged in isolation.

      --
      Don't piss off The Angry Economist
    7. Re:Slowaris caused threading by ceoyoyo · · Score: 1

      If you're using some sort of memory management so your pointers don't go all over the place then you have EXACTLY the same situation.

      Got a problem in one thread? Okay, the calculation that thread was doing goes MIA. Got a problem in some process? Same result.

      The problem is not with threads. It's with the half assed way they're usually implemented.

      Take a look at a distributed object system sometime. An object can be executing on the same thread, a different thread, a different process, or a different machine, and there's absolutely no difference as far as the programmer is concerned.

  23. My eyes glazed, by Anonymous Coward · · Score: 0

    since you know anything entitled 'considered harmful', as they are the ones actually harmful.

  24. Especially if you are organic matter... by Corf · · Score: 1
    --
    The pain was excruciating and the scarring is likely permanent, but that just means it's working.
  25. Threads are not harmful by Shinobi · · Score: 1

    A combination of specific implementations of threading and developers who use programming methodologies that were outdated already when the PDP-11 actually reached the market is.

    As a comparison, I learned to program properly on the Amiga, and its OS was natively threaded, and the architecture actually encouraged it(Likewise, unlike so many people who grew up with PC's, I also feel at home with programming for something like the PS3 or similar), and therefore I inherently think about how things can be split up, suitable algorithms etc. That's not to say that I always use threads, however.

  26. more detailed analysis from two years ago by somepunk · · Score: 2, Informative

    By Edward Lee of the EECS department at Berkeley: http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-1.html. Worth reading if you work with threads.

    --
    Those people who think they know everything are a great annoyance to those of us who do. (Isaac Asimov)
    1. Re:more detailed analysis from two years ago by pintpusher · · Score: 1

      Wow, my cs education must be working... I could actually understand that thing!

      Great read, thanks.

      --
      man, I feel like mold.
  27. Re:How about "C++ threads considered harmful"? by chez69 · · Score: 1

    exactly. I've written some very complicated threaded programs in java. The java.util.concurrent package has some really nice abstractions that make it much easier.

    I don't get all the dissing of threads around here (my 5 or so years of experience with threads are in the java world). with a little planning, they are not that hard to program. It almost sounds like the folks that couldn't understand pointers now matter how many different ways you explained them.

    --
    PHP is the solution of choice for relaying mysql errors to web users.
  28. Threading is a tool not a panacea by davidwr · · Score: 1

    Like Gotos, threads are a tool not a panacea.

    If you have a task that requires parallel operations, you should pick the best tool for the task. This might be separate computers, separate virtual computers, separate processes, separate threads, or even a roll-your-own system for managing your task where the operating system sees your task as a single thread in a single process.

    Of course, if you want to take advantage of multiple cores or multiple CPUs, the roll-your-own approach may not be an option in your OS.

    --
    Knowledge is how to play a game, intelligence is how to win, wisdom is knowing what game to play.
  29. The danger of higher-level thread functions by MikeRT · · Score: 1

    is that they may put threading problems beyond the control of the developer. What happens when your language environment has bugs in how it generates and manages threads? How much control would you have over what is being done behind the scenes? For that reason alone, I think it would be better to keep the use of threads purely optional, preferably as part of a library, rather than put into the core language itself as a series of features and keywords.

    1. Re:The danger of higher-level thread functions by marcosdumay · · Score: 1

      What happens when your language environment has bugs in how it generates and manages threads?

      You fix the environment.

      How much control would you have over what is being done behind the scenes?

      How much do you want? If the environment was able to balance processor usage, communicatin overhead and responsiveness, why not use it? Do you schedule your programs manualy nowadays?

      Too bad there isn't a viable alternative to hand made threads/processes.

    2. Re:The danger of higher-level thread functions by tepples · · Score: 1

      What happens when your language environment has bugs in how it generates and manages threads? What happens when your language environment has bugs in how it generates and manages arrays?

      For that reason alone, I think it would be better to keep the use of threads purely optional, preferably as part of a library, rather than put into the core language itself as a series of features and keywords. On which computing platforms will this library work, other than just Microsoft, Apple, and GNU platforms? Will it be available for use in both free and non-free software?
  30. Re:How about "C++ threads considered harmful"? by Poltras · · Score: 1
    What's more, immutable types are intrinsically exception-safe, thread-safe and (normally) garbage collected (in C++ even more, when a String object is declared on stack and freed in its constructor). What's more, if using reference counting and copy-on-write, you have no slow down (most cases it's faster). Dunno why people haven't learn that yet...

    I've been working with Cocoa/Objective-C for a while, and I'm starting to develop some of its habits in C++ (immutable strings, smart pointers, Copy-on-Write objects). I don't even need TLS most of the time.

  31. "Threads" are not the problem. by jythie · · Score: 2, Interesting

    The problem is that programmers are generally untrained in them or trained very poorly.

    Writing a safe threaded application is not a difficult task, but it is a different task then writing a single-threaded app. And unfortunately CS programs, books, tutorials, etc, still train people in the single-thread mindset and yes the programs they produce end up being buggy.

    And I'm not sure these 'high abstraction' languages are really the 'answer'. I have found that often in higher level solutions the results become even less predictable and tracing what is actually happening when becomes either extremely difficult, extremely inefficient, or just back to the single-thread mentality.

    I think the OP talking about how one might be next writing a parrell app shows the real flaw here... the author is going from one mentality, entering another without really thinking it through, and then complaining when old methods don't work well. Take a programmer who STARTED in parrell space and you don't run into these problems.

    1. Re:"Threads" are not the problem. by Panaflex · · Score: 1

      I agree 100 percent!

      The problem isn't with threading - it's how developers approach threading.

      All shared write structures must have locking! Use global variables sparingly - perhaps only for communicating exit procedures.

      And if you can - use a garbage collector. Seriously - if you're not tied to real-time transactions, a GC is the way to go.

      --
      I said no... but I missed and it came out yes.
    2. Re:"Threads" are not the problem. by jythie · · Score: 1

      *nods* I love ObjC's retain/release GC style for threading.

      I actually think a good set of 'training wheels' for getting developers thinking about threaded environments is to introduce them to fork with anonymous shared memory. Much easier to encapsulate things but still teaches how think in terms of multiple threads.

    3. Re:"Threads" are not the problem. by tepples · · Score: 1

      Seriously - if you're not tied to real-time transactions, a GC is the way to go. What are personal computers used for nowadays? Audio is real-time. Video is real-time. Games are real-time, except perhaps solitaire and the Civilization series.
    4. Re:"Threads" are not the problem. by Panaflex · · Score: 1

      True - but you can always manually schedule a cleanup in those situations. I don't see how a GC would impact overall performance, except perhaps in games.

      Real-time transactions have timing requirements - but even then I have been able to utilize a GC in such an environment.

      --
      I said no... but I missed and it came out yes.
  32. Re:How about "C++ threads considered harmful"? by ezzzD55J · · Score: 3, Funny

    (in C++ even more, when a String object is declared on stack and freed in its constructor) Sounds a bit soon :)
  33. Re:How about "C++ threads considered harmful"? by Arslan+ibn+Da'ud · · Score: 2, Interesting

    The problem with Java concurrency and threading is, all the locks are advisory. The synchronize statement is a nice bit of syntax, and making it apply to whole blocks of code was the Right Thing to do.

    The problem simply comes in that a program is not obligated to *use* synchronize, or any locking, when it accesses objects. Which means the code is totally unsuitable for integrating into a multithreaded program. And trying to backport thread-safety in is (currently) too difficult, as there are no tools to tell you when you've got it right.

    I haven't studied Erlang yet, but threads (or more generally concurrency) done securely would require mandatory locking of all data..except when you know two threads must share data and sync between each other. Ada95 seems to understand this, although it probably needs refinement.

    Which makes threads functionally equivalent to UNIX processes & shared memory :)

    --

    Practice Kind Randomness and Beautiful Acts of Nonsense.

  34. Stay Away from Parallelism!! by Alexpkeaton1010 · · Score: 1

    That way you CSers won't take over my turf as a FPGA designer.

  35. Re:Probably the first relevant "first post" I've s by aproposofwhat · · Score: 1

    I'm sure a diet would help :P

    --
    One swallow does not a fellatrix make
  36. Right. Mod parent up. by Animats · · Score: 2, Interesting

    The problem is not threads per se, but the way they are generally used in programming languages like C and C++

    Right. C and C++ provide zero help in dealing with the isolation issues of threading. The languages have no concept of parallelism (there's "volatile", but that's about it.) There were 1980s languages that did offer some help, such as Modula I/II/III, Ada, and Occam. Java has some minimal concurrency support, although it's not well thought out.

    There's nothing wrong with multithreaded programming, but some help from the language would be nice. Major issues with threads are "which thread owns what", "which locks lock what data", and "what can I safely call concurrently". C and C++ do not help here. They push the problem off to the operating system, which has no idea what to do about thread level data ownership.

    At the operating system level, we're not doing too well either. One good way to write concurrent programs is with multiple intercommunicating processes. Unfortunately, the Unix/POSIX/Linux mechanisms for interprocess communication are awful. You have byte-oriented pipes, sockets, and the seldom used "system V IPC" mechanism. None of these let you do something like an inter-process subroutine call. Subroutine call mechanisms built on top of these stream-like channels tend to be slow, clunky things like CORBA and SOAP. Windows does a bit better, but their fast approach is a legacy from OLE, which was designed for Windows 3.1 on DOS, and their slower approachs are more like SOAP. QNX has usable interprocess messaging, but few non-real-time systems are designed for QNX.

    I've been writing heavily concurrent programs with threads since the 1970s. It's possible to do it well, but the tools have not improved much.

    1. Re:Right. Mod parent up. by LizardKing · · Score: 2, Informative

      If you're familiar with CORBA, and underwhelmed by SOAP, then you might like to check out ICE. It's an attempt to do CORBA "better" - in other words, without the designed by committee and everything bar the kitchen sink aspects that ruined CORBA. I was initially a little bit sceptical, but having played around with it for a notifications system I've become really impressed.

    2. Re:Right. Mod parent up. by Animats · · Score: 1

      you might like to check out ICE

      There are lots of little IPC packages. Too many, actually. OpenRPC is somewhat dated, but OK. The last time I had to do this, I used Python, CPickle and pipes. But that wasn't a IPC-intensive application. When we did a robot vehicle for the DARPA Grand Challenge, there were about 20 processes communicating via QNX MsgSend/MsgReceive, and that worked out well, including dealing with hard real-time constraints, heavy computation on the same CPU as low-level hard real time control loops, and video over IPC. That's why I'm impressed with QNX RPC.

      A major problem in the Unix/Linux world is that there's no decent IPC system that's always there, always on, and used for almost everything. At least Windows has OLE. Gnome and OpenOffice both use CORBA, but have each has its own, incompatible, CORBA ORB. That kind of thing is part of the problem.

    3. Re:Right. Mod parent up. by dodobh · · Score: 1

      Multi process event driven programming, with lightweight message passing.

      Don't call a method in the other process, send it data instead.

      --
      I can throw myself at the ground, and miss.
  37. Re:How about "C++ threads considered harmful"? by dintech · · Score: 1

    Agreed. Threading isn't especially hard if you think about it first. If you stumble around like a donut then you're going to break thread-safety all over the place. This guy seems very alarmist to me. What's next? Space shuttles considered harmful?

  38. Single thread but multi core? by DaveV1.0 · · Score: 1

    Yeah, why write programs that can actually take advantage of multicore processors. That is just crazy talk.

    Just like BeOS was a crappy, low performance O/S.

    --
    There is no "-1 offended" or "-1 you don't agree with me" mod options for a reason.
  39. Re:How about "C++ threads considered harmful"? by Jellybob · · Score: 2, Interesting

    I haven't studied Erlang yet, but threads (or more generally concurrency) done securely would require mandatory locking of all data.


    I may have misunderstood (I'm not exactly an expert in threading), but I believe that Erlang handles this is a scarily elegant manner... once assigned, a variable can not be changed.

    The = operator in Erlang should be looked at in the mathematical sense, so the following (pseudo) code would fail:

    a = 2
    a = 1 + 3

    Because 1+3 != 2

    (Disclaimer: I've briefly dabbled in Erlang, but anything I say about it should be taken with several rocks of salt)
  40. Can someone explain why threads are useful? by azgard · · Score: 1

    I don't understand why threads are useful, except if you have multiple processors (and then, I don't see why you would need more threads than how many processors you have). OK, maybe for GUI, it is useful if the work of the program and the GUI are handled by separate threads. It always seemed to me that, on single processor, it is easier and faster to do the work required in sequential fashion than to use multiple threads (for online applications, you would split the work into time-bounded atomic operations, so one long transaction won't block the others from finishing).

    1. Re:Can someone explain why threads are useful? by Timothy+Brownawell · · Score: 1
      They're useful because

      foo () {
      // do stuff
      blocking_operation()
      // do other stuff
      }

      is nicer to work with than

      foo1 () {
      // do stuff
      when_done(async_operation(), foo2)
      } foo2 () {
      // do other stuff
      }

      , espicially if you have lots if local variables used by both "do stuff" and "do other stuff". It doesn't really matter for this use whether the compiler maps the first example to the second example or to OS threads.
    2. Re:Can someone explain why threads are useful? by 2short · · Score: 1

      "I don't understand why threads are useful, except if you have multiple processors"

      OK, but are you suggesting multiple core processors are, at this point, rare? Yes, threads are only really useful if you have the sort of processor most new computers have.

    3. Re:Can someone explain why threads are useful? by Anonymous Coward · · Score: 0

      "Yes, threads are only really useful if you have the sort of processor most new computers have."

      Nope, thats not true.

      I've seen code, both procedure and object oriented, that was a complete mess because the programmer attempted to interleave many unrelated contexts into a single line of execution and some nonsense style of internal context swapping implemented using structures. In these cases threads allow discretely managed contexts with defined communication paths to be developed as independent execution units of code that are much cleaner and more maintainable.

      When you move beyond trivial applications to those that require contrainable complex behavior and support for concurrent instances of the same code sequences, swapping between threads is much easier to debug and maintain then some form of internal context timeslicing designed by the random developer.

    4. Re:Can someone explain why threads are useful? by TummyX · · Score: 1

      Without threads you end up with multiple distinct tasks all interleaved into one massive while loop or something. It's terrible. Threads allow you to deal with seperate issues individually as if they are a single flow of execution. I regularly use more than 10 threads for desktop applications. They allow me to responsive applications or just as importantly, applications that give the appearance of responsiveness.

      Nothing is worse than a UI that stops responding because the programmer decided to do heavy processing work in the UI thread.

      I've never really understood why a forum of "geeks" are so negative about threads. Maybe everyone here aren't as good at programming as they would like to believe.

      Writing threaded programs is not hard. It just requires proper training or experience (just like anything else).

    5. Re:Can someone explain why threads are useful? by 2short · · Score: 1

      Why does someone use so many big, BS-laden words and not log in? You don't know what you're talking about, as I'd be happy to explain, but I've sworn off making substantive replies to ACs. Sigh. The idiocy level is tempting, but no, I must be strong.

  41. Web server w/o processes OR threads... by Dr.+Manhattan · · Score: 3, Informative

    Unix's select/poll mechanism avoids all that. See, e.g., here.

    --
    PHEM - party like it's 1997-2003!
    1. Re:Web server w/o processes OR threads... by tepples · · Score: 1

      Right, select() was fine in the single-core days, but an application with a single process with a single thread won't utilize more than about one-fourth of a quad-core server. What do you plan to do with the other three cores, or with the time that the server process spends waiting for the disk?

    2. Re:Web server w/o processes OR threads... by dkf · · Score: 1

      Right, select() was fine in the single-core days, but an application with a single process with a single thread won't utilize more than about one-fourth of a quad-core server. What do you plan to do with the other three cores, or with the time that the server process spends waiting for the disk? With the other cores, you can be doing processing relating to dynamic webpages (the main server can be handling other requests in the meantime) and the server process should be handling disk IO also in an asynchronous manner. Get that sort of stuff right (not too hard to do) and virtually all the processing is done in IO hardware with just the occasional bit of coordination by the CPU. Which is exactly how IO-bound processing is supposed to work!

      Or would you rather have all four cores spinning on the spot waiting for IO?
      --
      "Little does he know, but there is no 'I' in 'Idiot'!"
    3. Re:Web server w/o processes OR threads... by Dr.+Manhattan · · Score: 1

      ...an application with a single process with a single thread won't utilize more than about one-fourth of a quad-core server. What do you plan to do with the other three cores...

      Run CGIs and the database.

      --
      PHEM - party like it's 1997-2003!
  42. All About Speed by Anonymous Coward · · Score: 0

    Telling girls their threads are harmful is the fastest way to get their clothes off

  43. Threads work fine by mugnyte · · Score: 2, Interesting
    Going beyond what you state - indeed I agree: Threads have a useful place in the toolbox. Perhaps this will mark me as "old" at some point in the world of programming.

      I use them routinely on MS platforms. Background threads for write-behind mechanisms, for self-tuning caches, for animation. The sharing between threads is the more-precise problem, not threads itself. If one knows how to examine the context of a thread, one can see all shared pints and code accordingly. This is no different that knowing what pieces of data are eventually exposed as public data of a component.

      That said, there is a clumsy set of constructs around threading still. Most modern languages do not have the atomic test-and-flip operation around an object as you wish. For example, in the C# realm, I see this routinely:

    if ( !sharedMemInitialized ) {
        lock( sem ) {
          if ( !sharedMemInitialized ) { // awkward
     
    // ...................initialize
    ...I'd much more appreciate the OS supporting a thread-level operation that allowed for

    sem.LockIf( !sharedMemInitialized ) {
     
    //................ initialize
      }
    ..where above clause was skipped if (sharedMemInitialized==true), and if not, it waited for the "sem" semaphore concept to be unlatched.

    1. Re:Threads work fine by ChatHuant · · Score: 1
      That said, there is a clumsy set of constructs around threading still. Most modern languages do not have the atomic test-and-flip operation around an object as you wish. For example, in the C# realm, I see this routinely:

      [snip]

      ...I'd much more appreciate the OS supporting a thread-level operation that allowed for


      sem.LockIf( !sharedMemInitialized ) {
      //................ initialize
      }


      ..where above clause was skipped if (sharedMemInitialized==true), and if not, it waited for the "sem" semaphore concept to be unlatched.

      So what's wrong with the Interlocked class? It seems to do exactly what you want:

      if (Interlocked.Exchange(ref sharedMemInitialized, 1) == 0){

      // Initialization
      }


      You can see more details and a locking example using that technique here
  44. Re:How about "C++ threads considered harmful"? by larry+bagina · · Score: 2, Interesting

    In Erlang, variables aren't variable -- they're single assignment. (There is a process dictionary that is mutable, but it isn't usually used and other threads don't have access to it). Inter-thread communication is done via message passing (which may be local or over tcp/ip).

    --
    Do you even lift?

    These aren't the 'roids you're looking for.

  45. That's not disagreeing with Dijkstra by Anonymous Coward · · Score: 4, Insightful

    I know nobody born in the last 30 years has bothered to read his memo, but he doesn't pretend gotos are "evil". Just that people should adopt structured control flow structures instead. Meaning, design and use languages with such advanced features as "if/else" statements, and "while" loops, and "functions". Goto considered harmful was written in a time when most people were not using the fancy new languages that offered these features, and he was suggesting that they do so, in order to improve the quality of their code.

    Unless you seriously think people should use gotos instead of loops and if/else statements, then you don't disagree with Dijkstra.

    1. Re:That's not disagreeing with Dijkstra by Hognoxious · · Score: 1

      I know nobody born in the last 30 years has bothered to read his memo
      Pesky kids! Goto somewhere that isn't my lawn!
      --
      Confucius say, "Find worm in apple - bad. Find half a worm - worse."
  46. Almost All Web Servers Are Multi-Threaded by TheNarrator · · Score: 1

    Every web server that can handle more than one client simultaneously is basically multi-threaded. Its painfully clear that threads have been an enormously successful programming model and are here to stay. Concurrency is difficult to understand but that doesn't mean it's not necessary.

    1. Re:Almost All Web Servers Are Multi-Threaded by Just+Some+Guy · · Score: 1

      Every web server that can handle more than one client simultaneously is basically multi-threaded.

      Snort.

      --
      Dewey, what part of this looks like authorities should be involved?
  47. F90 and SIMD by TeknoHog · · Score: 1

    I've already said this about a dozen times on /., but here goes anyway ;)

    In 2001 I worked at CERN, writing simulation and analysis software on a dual P3 machine. The language was Fortran 90, and the compiler made use of SIMD (MMX/SSE) on both processors to parallelize matrix algebra.

    The parallelism was abstracted away quite nicely, just as the article suggested. There was probably some thread/process creation under the hood to make use of both CPUs, but the calculations were basically SIMD in nature. F90 handles matrix math natively, so there's no guesswork involved with the "parallelizing" compiler. (I put that in quotes, because the code is already parallel, unlike loops in C.)

    There's a lot of processing that has this SIMD-like parallelism, for example sound and video work, and with the correct tools it's easy to expand SIMD from one CPU to many.

    --
    Escher was the first MC and Giger invented the HR department.
  48. Parallelism mimicks the physical world by Cthefuture · · Score: 1

    If we are to have any hope of using computers to solve the most interesting problems then we will eventually be using parallelism on a massive scale. This is how the physical world works. All those atoms and particles swirling around you are not a serial batch process.

    --
    The ratio of people to cake is too big
  49. Re:Threads in Windows vs. *NIX by Anonymous Coward · · Score: 1, Informative

    CreateProcess() in Windows is very heavy weight. exec() in *NIX is heavy weight.

    fork() in *NIX is light weight in any modern (post 1980) OS. Doesn't exist in Windows.

    SpawnThread() in Windows is light weight. In *NIX it is a special case of fork()

  50. Single Threading Is Harmful by MOBE2001 · · Score: 1

    My point is that a thread is a thread. If using multiple concurrent threads is harmful, so is using a single thread. Single threading is less harmful than multithreading but harmful nonetheless. The thread is the reason for every ill that ails computing, from the reliability crisis to the parallel programming crisis. There is a way to design and program computers that does not involve threads at all. It's called the non-algorithmic software model. This is the way we should have been doing it in the first place. To find out why algorithmic software (threading) is the work of the devil, read the articles at the links below:

    Parallel Programming, Math and the Curse of the Algorithm
    Why Software Is Bad and What We Can Do to Fix It
    Nightmare on Core Street

    150 years after Babbage and Lady Ada introduced the algorithmic computing model, it is time to change. The longer we wait to realize the folly of our ways, the worst our problems are going to get.

    1. Re:Single Threading Is Harmful by twistedcubic · · Score: 1

      What is this "non-algorithmic software model" you speak of? Your blogs don't seem to give a specific example of anything.

    2. Re:Single Threading Is Harmful by MOBE2001 · · Score: 1

      What is this "non-algorithmic software model" you speak of? Your blogs don't seem to give a specific example of anything.

      Good question. I agree that the definitions should be more visible on the blogs.

      In an algorithmic program, every element (instruction or operation) sends a signal to a successor element saying essentially, "I'm done, now it's your turn". Communication is thus one-dimensional. That is to say, an element can have only one predecessor and one successor.

      In a non-algorithmic program, by contrast, communication is multidimensional, i.e., there is no limit to the number of successors or predecessors that an element can have.

      Non-algorithmic programs are intrinsically parallel and deterministic. Two examples of non-algorithmic systems are: neural networks and logic circuit simulations. I believe that computing will not come of age until processors (both single and multicore) are designed to directly support non-algorithmic software.

    3. Re:Single Threading Is Harmful by Jamie+Lokier · · Score: 1

      That's also called dataflow programming.

      Lazy functional programming is very similar to it.

    4. Re:Single Threading Is Harmful by MOBE2001 · · Score: 1

      That's also called dataflow programming.

      Sorry, but I don't think so. A neural network (or a cellular automaton) is not a data flow program. A more accurate label for non-algorithmic programming would be control flow programming. It's not about the data but the control signals. That being said, I don't like the name 'control flow' either. This software model is better described as a non-algorithmic, synchronous reactive model. The word 'flow' does not convey its true meaning.

    5. Re:Single Threading Is Harmful by Jamie+Lokier · · Score: 1

      You're right, those sorts of systems wouldn't fit the definitions of dataflow programming. I wouldn't call all of them non-algorithmic - cellular automata can be highly representative of an algorithm and constructed specifically for one.

      Although I agree that the name 'control flow programming' isn't very nice, I like the idea it invokes for me that the control relationships move with the data, and in a way which is not predetermined by a static control structure (i.e. a classical algorithm). I believe you can take this further, intertwining the control and data structures such that they are indistinguishable and flow, with the substrate governing the flow but not necessarily the computation.

      These ideas are old in sci-fi, but I'm not aware of them being used in real devices to any notable extent. I have occasionally considered doing a PhD on exactly this topic - what a nice coincidence :-)

    6. Re:Single Threading Is Harmful by rp · · Score: 1

      This is not a new idea. Petri nets, communicating state machines, actors, etc. were developed in the 70s or earlier.

      BTW, colored Petri nets (from the 1980s) unite data flow and control flow: control flow just becomes dataflow with "void" data.

    7. Re:Single Threading Is Harmful by Jamie+Lokier · · Score: 1

      Indeed, they are old ideas. But have they been used in real devices to any notable extent?

  51. "Considered harmful" considered harmful by Quattro+Vezina · · Score: 1

    The phrase "considered harmful" implies that there is a large community consensus that something is considered harmful.

    But it's never used like that; it's always used by one opinionated loudmouth who is the only one in the world who considers the practice harmful. You want another example? Look at that crock of an essay "Reply-to munging considered harmful"; the only one who considers reply-to munging harmful is the opinionated loudmouth who wrote that essay, yet the title falsely implies that the community as a whole has decided reply-to munging is harmful.

    It's a phrase filled with sound and fury, an attempt to deceive people into thinking there is a consensus when there is none.

    --
    I support the Center for Consumer Freedom
  52. Well no shit by skulgnome · · Score: 1

    But you had to have "lightweight processes" aka threads, because apparently even copy-on-write forking was "too expensive". Now what's expensive, you dickbags? Huh? Programmer time or time spent debugging weird implicit sharing bugs?

    Of course threads are still quite nice. Problem is, most "programmers" today are little more than monkeys who hurl feces at the computer. These people cannot be expected to understand threads. Most of them do not understand database transactions, or any kind of concurrency!

    However, the technology should not be blamed for its misuse by idiots.

  53. Re:Threads in Windows vs. *NIX by abigor · · Score: 1

    SpawnThread() in Windows is light weight. In *NIX it is a special case of fork() Isn't it still createthreadex() on Windows or something?

    Threads on Linux (using NPTL) are actually a result of clone().
  54. Two years in the future by Anonymous Coward · · Score: 0

    I used a "goto" in a pthread. A Time-space bubble formed and transported me back in time, just to read this article. So now, thanks to the author I can now avoid my own "Ground Hog Day".

  55. Re:How about "C++ threads considered harmful"? by Poltras · · Score: 1

    Damn. Thanks for solving all the bugs in my current project ;-)

  56. locking is the problem - is (S)TM the answer? by burris · · Score: 1

    The root of the problem is shared state, operations on shared state need to have ACI properties - atomic, consistent, and independent. Some languages / environments, like Erlang and QNX, solve this problem by basically getting rid of shared state and making all threads communicate with each other over socket-like abstractions. With common programming languages the solution is mutually exclusive locks. You lock up the memory you're working on then unlock it when you're done.

    Locks have problems. In order to get good concurrency, you need fine grained locking. Once you have multiple resources protected with multiple locks you run into gotchas like deadlocks and race conditions. There are also issues with exceptions and programmer mistakes causing locks to remain locked or unlocked. All of this can make it very difficult to reason about what is happening in your program and you can end up with bugs that are very difficult to reproduce and/or fix. Locking is also pessimistic - you pay for the cost of locking even if nobody else is looking at the same pieces of memory while you are. Finally, you can't necessarily compose two operations that use their own locks.

    A relatively new approach is (Software) Transactional Memory. This is an optimistic method that doesn't use locks. Instead its more like an in-memory database transaction that provides atomic, independent, and consistent access to a set of shared variables. Shared variables have versions associated with them. When you start a transaction the runtime records the versions of the variables. Then after reading and/or writing all the variables in the transaction the runtime compares the current versions with the originally recorded versions. If they are the same the transaction commits and you continue, otherwise the runtime "rolls back" the changes and retries (or doesn't retry, you get control over that if you want.) The cost for uninterrupted reads and writes is very low, you only pay a higher recovery cost when there is an actual conflict.

    There are STM libraries available for many popular languages (C#, C++, Java, Ruby) but the most mature and elegant support seems to be in Haskell. Since Haskell is a pure functional language, all side-effects are encapsulated in monads. Because of this encapsulation enforced by the language, it's impossible to actually read or write any transactional variables outside of a transaction. Reading or writing a transactional variable "infects" that function and every calling function until the data is safely brought out of shared memory locations by a transaction. The rest of your code is already thread safe because it doesn't have shared state. The compiler keeps you safe and type checks everything.

    There are a bunch of papers you can check out as a starting point. I think this is definitely the future of multithreaded programming.

    1. Re:locking is the problem - is (S)TM the answer? by Pinky's+Brain · · Score: 1

      Do you know of any papers which applied it to something a little more adventurous than list sorting?

  57. JoCaml by mossr · · Score: 1

    JoCaml is an extension of OCaml that supports concurrent and distributed programming through the use of the Join Calculus. Unlike other, more well known, process calculi such as CCS and Pi-Calculus, Join Calculus was design to allow efficient implementations.

    The basic model is message passing (ala Erlang), but the killer feature is that you can specify "joins" -- think of them as functions that get called when a specific combination of messages are received. I managed to convert a single-threaded simulation into a parallel version that distributes over an arbitrary number of cores/computers in less than three hours. I'm not saying it's a silver bullet or that it's ideal for your next project, but it worked damn well for me. The underlying calculus could be implemented in other languages, although it probably works best in languages with good match statements, such as OCaml and Haskell.

    --
    The PowerPC includes for this purpose two instructions called SYNC and EIEIO.
    1. Re:JoCaml by rp · · Score: 1

      See also Polyphonic C#.

  58. The Actor model is the solution by master_p · · Score: 2, Interesting

    The Actor model, where each object is a separate thread, is the way to the future. When an actor sends a message to another actor, the message is stored in the target actor's message queue and the thread that represents the target actor is woken up to process the message. Results are delivered with future values.

    With the Actor model, whatever data parallelization is there in a program is automatically exposed.

  59. Except ... by Pinky's+Brain · · Score: 2, Insightful

    Functional programming is hard, non intuitive and even plain distasteful to me. Now I know I'm an idiot, but the problem is most programmers are idiots. The language has to make parallelism easy for us, and if it starts out being functional it's already lost that battle.

    1. Re:Except ... by SanityInAnarchy · · Score: 1

      That is one of many, many things I find wrong with Erlang, although I would suggest that a good book on Erlang will help a lot. Erlang isn't purely functional, and it is actually pretty easy to pick up.

      But Erlang also has horrible syntax, not particularly good Unicode support, and all the other problems you'd expect from a language that isn't popular. I'd much rather steal Erlang's message-passing and use it in another language.

      And message-passing really is a good deal more intuitive than locks, semaphores, and all the other threading things. Threading is hard. Doing it shared-nothing, as processes, is much easier.

      --
      Don't thank God, thank a doctor!
    2. Re:Except ... by Fry-kun · · Score: 2, Interesting

      Who was it that said that "Computer Science" was the worst thing to happen to both computers and science?

      Right now, everyone thinks in terms of Turing Machines - we tell the computer what to do. In functional programming, you tell the computer what result you want to achieve (in terms of formulas and such) - and it does it for you.

      It's hard to grasp for someone who's used to the Turing way, but it's not for someone who hasn't dealt with it. Programmer should be able to give hints to the CPU (for optimization, etc.), but not detailed instructions as we do now.

      --
      Did you know that "FTW" ("for the win") is a direct translation of "Sieg Heil"?
  60. Re:How about "C++ threads considered harmful"? by TheRealMindChild · · Score: 1

    There are circumstances where threads are completely inappropriate. Let's say that you were hoping to build an app, that eventually would scale across a single-image cluster farm (for those not in-the-know, this isn't a beowulf cluster, but rather a cluster that you would add a new "node" to, that would then be treated as part of the collective resources of the single "machine". See SSI). Unlike on your single machines, a thread can not practically be migrated to a new "processor" on a different node, because the entire process space would need to be copied when the migration happens. Not to mention, think about a thread changing information in its parent processes space. All of a sudden, you would need to stop the processing of any other threads with the same parent process, on different nodes, sync the memory, then signal them to continue. It would practically make the whole idea of performance clustering useless.

    --

    "When life gives you lemons, don't make lemonade. Make life take the lemons back!" -- Cave Johnson
  61. Re:How about "C++ threads considered harmful"? by Pinky's+Brain · · Score: 1

    Shared memory leaves too much control in the hands of the developer needlessly. A lot of the time there really is no need for 2 processes to be able to write to the same data at the same time, yet shared memory makes this situation default and leaves the developer to make sure it doesn't happen.

    It should be the other way around, the developer should have to work harder to be able to get into that situation ... not merely forget to check a condition.

  62. X considered harmful by Xtifr · · Score: 1

    Indeed, "X Considered Harmful" is such a common title that the Jargon File has a whole entry for it. And the entry, of course, cites Djikstra as the inspiration for the meme. (Others have disputed this, and claim it was common in mainstream journalism even earlier, but Djikstra's famous essay clearly put the phrase on the map in the CS/IT world.) Merely using the phrase hardly indicates that a comparison to Djikstra's classic work is necessary or justified.

    There has been, at least according to the aforementioned Jargon File, an essay in CACM called "GOTO Considered Harmful" Considered Harmful. I have to wonder if we don't need an essay simply titled "Considered Harmful" Considered Harmful". :)

    Furthermore, the Slashdot summary is (as usual) badly flawed: Knuth didn't say that threads were harmful, he simply said that he didn't find them useful. Not that I want to defend threads--I've pulled out enough of my own hair because of them--but, as long as we're on the topic of inappropriate comparisons.... I don't know who this James Nobody is, but I'm pretty sure that he's not in the same league as Djikstra or Knuth, and the inappropriate and misleading attempts to convince me that he his makes me less, not more, interested in reading TFA.

  63. Shared State Considered Harmful by argent · · Score: 1

    The problem isn't threads, it's threading models that depend on shared state to communicate between threads. If you explicitly pass data between threads using a message paradigm you get most of the performance advantages of threads with the ease of programming in independent processes. Design the code around a model like message passing (as in the Amiga Exec, which was really a threaded share-everything environment, or QNX) or a database-style access method (which is what I've been doing in speedtables) and you can implement it using threads or processes, SMP or not, single-host or networked, depending on the requirements.

    You don't necessarily need fine-grained locking to do this, depending on the design.

    Sometimes shared state is desirable, just as sometimes gotos are desirable, but only in the context of a structured framework (structured programming, message-based intertask communication) where they're the exception rather than the rule.

  64. finite state machine by Anonymous Coward · · Score: 0

    Do they not teach people how to write state machines any more? Any application that needs to deal with a fixed set of discrete events can easily be modeled as a finite state machine and implemented in a single process.

  65. and btw: Dijkstra did not use the phrase by gwniobombux · · Score: 1
    As you can see from http://www.cs.utexas.edu/~EWD/transcriptions/EWD13xx/EWD1308.html quote:

    Finally a short story for the record. In 1968, the Communications of the ACM published a text of mine under the title "The goto statement considered harmful", which in later years would be most frequently referenced, regrettably, however, often by authors who had seen no more of it than its title, which became a cornerstone of my fame by becoming a template: we would see all sorts of articles under the title "X considered harmful" for almost any X, including one titled "Dijkstra considered harmful". But what had happened? I had submitted a paper under the title "A case against the goto statement", which, in order to speed up its publication, the editor had changed into a "letter to the Editor", and in the process he had given it a new title of his own invention! The editor was Niklaus Wirth.
  66. having the full compliment of arrogance by museumpeace · · Score: 1

    that programmers are heir to, I would suggest that most people make hash out of single thread programming...we were doing that for years before we started working in the kernel. So, whats a little more complexity when we already HAVE to have ways to combat it in design and test tools?

    I suppose our confidence in driving toward parallelism rests on intuition, such as analogizing that the brains of all higher animals are parallel processors therefore some solution to the problems of parallel computation must exist. It is certainly a commonplace even among non-CS-literate folk that the brain is massively parallel.

    --
    SLASHDOT: news for people who can't concentrate on work or have no life at all and got tired of yelling back at the TV.
    1. Re:having the full compliment of arrogance by marcosdumay · · Score: 1

      I suppose our confidence in driving toward parallelism rests on intuition, such as analogizing that the brains of all higher animals are parallel processors therefore some solution to the problems of parallel computation must exist.

      That and because the uncertainty principle (that of quantum mechanics) says that we can't keep increasing the speed of our switches (transistors) forever.

  67. Re:How about "C++ threads considered harmful"? by SanityInAnarchy · · Score: 1

    The main problem I have with Java threads, vs Erlang, is that Java threads are still using locks. They're locks with nice syntactic sugar on them, but locks nonetheless.

    --
    Don't thank God, thank a doctor!
  68. Re:How about "C++ threads considered harmful"? by SanityInAnarchy · · Score: 1

    Sounds like a case designed for Erlang.

    Erlang makes multithreading on the same machine easy, using a message-passing model. If you need to connect to a remote machine, you can do that pretty much as easily. It would work well on a Beowulf cluster.

    I'm not sure how well it would work on a "single-image cluster farm", but I don't see why it would be any harder to create multiple Erlang processes on the same "machine" and have them pretend to be remote.

    --
    Don't thank God, thank a doctor!
  69. Bias Disclosure by chadkennedyonline · · Score: 1

    James Reinders, the article's author, is the Intel marketing director for the company's Developer Products Division. The Developer Products Division is responsible for the Thread Building blocks (TBB) API, which is mentioned in the article as a solution to the "problem" presented. To his credit, Mr. Reinders does also mention OpenMP.

  70. Re:How about "C++ threads considered harmful"? by dumael · · Score: 1

    With Erlang you've got no shared data between threads (processes in Erlang terminology), along with immutable data. Both of these greatly simplify concurrency as you don't need locks. If you need a shared resource (such as a file or network socket), a trival way to implement it in Erlang is to have another process that simply acts as a interface between the resource and any other process(es). To communicate between processes in Erlang you use asynchornous message passing, and by design you can block or wait for a limited time to recieve messages. Have a look at the Actor model which Erlang implements: http://en.wikipedia.org/wiki/Actor_model

  71. Re:Threads in Windows vs. *NIX by sjames · · Score: 1

    Threads on Linux (using NPTL) are actually a result of clone().

    Clone is the fundamental op in Linux. fork is a special case of clone. Creating a posix thread is another special case of clone. Meanwhile, clone itself has a series of flags to allow for a broad spectrum from shared nothing (including namespace and expreimentally, pid space) to shared everything except cpu context. Posix threads are at one end while fork falls near (but not at) the other end with flags like CLONE_NEWNS, you can share even less than a fork call would.

  72. Re:How about "C++ threads considered harmful"? by StarvingSE · · Score: 1

    Just use OpenMP. Makes optimizing a program for parallel execution very easy.

    --
    I got nothin'
  73. You must be new here by Anonymous Coward · · Score: 0

    Welcome to Slashdot!

  74. "X Considered Harmful" Considered Harmful! by StCredZero · · Score: 1

    There's too many headlines concerning "X Considered Harmful"

    1. Re:"X Considered Harmful" Considered Harmful! by NateTech · · Score: 1

      Slashdot comments considered harmful.

      --
      +++OK ATH
  75. chickens by Viking+Coder · · Score: 3, Funny

    Q) Why did the multithreaded chicken cross the road?
    A) to To other the side. get the

    --
    Education is the silver bullet.
  76. Re:Threads in Windows vs. *NIX by abigor · · Score: 1

    Let me just say that I miss reading posts like yours on Slashdot. Well done, sir.

  77. Real-time constraints by tepples · · Score: 1

    On time and stable trumps 3% faster with deadlocks a year late *every single time*. Unless "on time" in terms of delivery of the software conflicts with "on time" in terms of real-time computing. A lot of times, you can't just throw more hardware at a problem because the software has to run on the hardware that the user already owns, and you don't have the infrastructure to distribute a single application as a hardware appliance.
    1. Re:Real-time constraints by Chandon+Seldon · · Score: 1

      If you're coding for cell phones, that may be relevant. When it comes to embedded systems the hardware is one of the design parameters that the developers control. For desktops, any reasonably modern system is fast enough that paying abstraction penalties is fine - if it's too slow you can use a different algorithm or make the task simpler.

      --
      -- The act of censorship is always worse than whatever is being censored. Always.
    2. Re:Real-time constraints by tepples · · Score: 1

      If you're coding for cell phones, that may be relevant. PDAs and gaming handhelds for the same reason.

      For desktops, any reasonably modern system is fast enough that paying abstraction penalties is fine - if it's too slow you can use a different algorithm or make the task simpler. Imagine a home theater PC trying to transcode multiple high-definition video streams in real time, one stream from each tuner. Would you want to ship a video codec whose inner loop is written in Python? Or how much of the codec would you rewrite in C++ as a Python extension module? "Us[ing] a different algorithm or mak[ing] the task simpler" might significantly increase the bit rate for a given subjective distortion level, causing the high definition to be lost or using much more disk space. Or in video games, "mak[ing] the task simpler" might result in Wii-level graphics on a platform that has seen Xbox 360-level graphics from another publisher.
    3. Re:Real-time constraints by Chandon+Seldon · · Score: 1

      Sure, in practice you optimize bottlenecks - frequently by writing modules in lower level languages. The same is true for concurrency issues - the amazing lock-free data structure or message passing primitives are going to be written in low level code (probably with assembly for atomic compare and swap).

      But... that doesn't change the fact that 99% of code will never need to be optimized like that, and trying to optimize code that doesn't need it usually just results pointless obfuscation and wasted programmer time (both to do it and to debug it later).

      --
      -- The act of censorship is always worse than whatever is being censored. Always.
  78. Completely Asinine by Secret+Rabbit · · Score: 1

    Threads aren't the problem. It's the retarded programmer that hasn't a clue as to how to use them that is the problem. It's like blaming guns for people shooting each other.

    Want threads to be safe? How about having enough grey matter to protect shared vars, etc with a mutex/semaphore/etc. Or how about making a thread only variable (man pthread_key_create, pthread_[get,set]specific). Hell, how about the crazy idea of keeping track of ones data flow.

    This sort of ridiculous thinking is only keeping us from getting the power out of our machines that we could. It's time people suck it up and learn to deal with REALITY. Multi-core/Multi-processor machines are only getting more so. To ignore that is just plain profound stupidity. Stop complaining and just learn how to do it.

    Well, at least there are some people out there that know how to think:

    http://cag.csail.mit.edu/ps3/

  79. Yes! Example: craftsman vs. assembly line by ulatekh · · Score: 1

    Exactly. A single-threaded program is like a craftsman. A concurrent program is like an assembly line. Humanity has only been doing assembly lines for over a century now, i.e. Henry Ford's car factory. It sure would be nice if we could bring computer programming up to the beginning of last century.

    Every other engineering discipline seems to be able to handle the concept. The only thing holding up the software world from embracing concurrency is our own collective lameness.

    --
    "Once we've identified and embraced our sickness, we'll have strength...and that's when we get dangerous." - John Waters
  80. Re:How about "C++ threads considered harmful"? by fbjon · · Score: 1

    AFAIunderstand, if all your shared objects are immutable, then you don't need to use locks at all. Only mutable shared objects need to be synchronised.

    --
    True confidence comes not from realising you are as good as your peers, but that your peers are as bad as you are.
  81. "Considered Harmful" Essays Considered Harmful by tepples · · Score: 1

    I have to wonder if we don't need an essay simply titled "Considered Harmful" Considered Harmful". Don't wonder. Read Eric A. Meyer's essay.
  82. Re:How about "C++ threads considered harmful"? by DragonWriter · · Score: 1

    I haven't studied Erlang yet, but threads (or more generally concurrency) done securely would require mandatory locking of all data.


    Erlang concurrency works through lightweight processes that don't share staet and can communicate only through special dedicated communications channels (or at least that's the high-level view; on a low level, I assume, though I haven't looked at the implementation, that in fact the communication channels have to be implemented as shared state with locking enforced by the language implementation.) Consequently, "thread-safety" is rendered into a non-issue.
  83. Re:Making a parrallel with Edsger Dijkstra's artic by DragonWriter · · Score: 1

    This is true, but TFA is still marginally useful in that the comments present a link to a more useful article which reflects the same general viewpoint as TFA but does make an argument and present alternatives:

    http://www.eecs.berkeley.edu/Pubs/TechRpts/2006/EECS-2006-1.pdf

  84. Does Ruby run on a handheld with 4 MiB RAM? by tepples · · Score: 1

    Oh, by the way -- "ensure", in Ruby, is a block which is guaranteed to run after the "begin" block finishes, exceptions or not. It seems to be the absolutely perfect, logical fit for what you're trying to do. That's the same as try/finally in Java or Python. But unfortunately, neither Java, Python, nor Ruby is usefully ported to my customers' platform, and I don't have the infrastructure to distribute brand new hardware to all of my software customers, let alone support it. It's either assembly language, C, C++ without iostream, or an order of magnitude speed hit and half the 4 MiB working memory taken by the interpreter.

    Seems to me, you end up with the exact same problems -- when does that goto happen? How do you make sure it gets called, and how do you make sure you catch the error condition properly? Don't 'return' from the function. Instead, when you would 'return', do 'goto ret', which calls the destructors as needed. I guess the real solution in this situation is to make RAII wrappers for the library_thing resources and let C++ destroy them automatically when they fall out of scope.
    1. Re:Does Ruby run on a handheld with 4 MiB RAM? by SanityInAnarchy · · Score: 1

      That's the same as try/finally in Java or Python. Right. I like to use my language of choice in examples; I'm less likely to get it wrong that way.

      It's either assembly language, C, C++ without iostream I see.

      But that's not a case for goto -- that's a case against languages that lack good exception handling. Or it's a case for adding a 'finally' clause to C++.

      Don't 'return' from the function. Instead, when you would 'return', do 'goto ret', which calls the destructors as needed. It seems like this would have the same problems. For example:

      int do_some_calculation(int a, int b) {
          return a/b;
      }

      #define ERROR -1

      void foo() {
          do_library_setup_stuff();

          int result = do_some_calculation(5, 0);
          if (result == ERROR) {
              goto ret;
          }

          do_something_with(result);

          ret:
          do_library_cleanup_stuff();
      }

      See the problem? You need to wrap it in a try block anyway -- or you need to wrap your resources in an object with proper destructors. I don't see what goto buys you, unless you can guarantee that exceptions won't be thrown.
      --
      Don't thank God, thank a doctor!
  85. RAII by tepples · · Score: 1

    finally Unlike in Java and Python, 'finally' is not present in C++. You have to simulate it with objects that own resources, so that their destructors perform the cleanup.
    1. Re:RAII by jgrahn · · Score: 1

      Unlike in Java and Python, 'finally' is not present in C++. You have to simulate it with objects that own resources, so that their destructors perform the cleanup.

      Of course, us C++ programmers phrase that a bit differently: "Unlike C++, Java and Python do not have RAII. You have to manually maintain 'finally' blocks everywhere where you may need to perform cleanup".

  86. Fancy programming languages are NOT the solution. by ulatekh · · Score: 4, Interesting

    I'm tired of reading replies to this article that evangelize some fancy-schmancy high-level solution. I wonder if these advocates have ever tried writing production code in such an environment.

    Let me give you a wonderful example of when theory simply doesn't meet reality.

    Recently, I wrote a bunch of multi-threaded code for a next-generation asymmetric-multiprocessing game console that shall remain nameless. Its operating system has a wonderful complement of synchronization features. There's the usual mutex lock/unlock, and the usual condition signal/wait, but there are also event queues (queues of generic events that can be passed between threads running on different types of processors), lightweight mutexes/conditions, spinlocks, semaphores, reader/writer locks, and so on and so on. Truly a rich palette from which one can paint a wonderfully synchronized multi-threaded application! I then proceeded to try to rewrite a key section of our code in a very multi-threaded way.

    The problem was, the first version of this code added NINETY milliseconds per frame to our main thread. A profile showed that nearly all of the extra time was spent in the operating system's synchronization features.

    After much rewriting and much pain, I stopped using all of the operating system's synchronization features, and used processor-level atomic operations instead, and finally, the extra code accounted for only FOUR milliseconds per frame in our main thread (with the rest of the time successfully farmed out to separate threads).

    I challenge anyone with a fancy-schmancy automatic concurrency solution to demonstrate that it doesn't have this problem.

    --
    "Once we've identified and embraced our sickness, we'll have strength...and that's when we get dangerous." - John Waters
  87. Obligatory reference by Anonymous Coward · · Score: 0

    In before Pern!

  88. Re:Fancy programming languages are NOT the solutio by EsbenMoseHansen · · Score: 1

    And of course, should you program ever run a multi-processor system, it will fail in all sort of subtile, non-predictive way. E.g., in all cases where a variable has been loaded into a register, but likely there are also cases involving caching to some degree.

    --
    Religion is regarded by the common people as true, by the wise as false, and by rulers as useful.
  89. Re:Fancy programming languages are NOT the solutio by Anonymous Coward · · Score: 0

    how about writing that up as an article for gamedev.net :)

  90. Re:Fancy programming languages are NOT the solutio by dkf · · Score: 1

    I'm tired of reading replies to this article that evangelize some fancy-schmancy high-level solution. I wonder if these advocates have ever tried writing production code in such an environment. There are different sorts of production environment, you know. Some value stability over raw speed, others like to emphasize short time-to-market. (Yeah, yeah, I know everyone actually cares about speed, stability, quick development, maintainability, etc. but you have to pick which things you stress, since that determines what corners you cut...)

    The truth is that threading is a professional power tool. Like any pro power tool, you have to be careful and know how to use it, or it will rip your arm off (well, metaphorically) but it does do what you tell it to and can lead to great results.

    Shared memory threading is basically just having two (or more) CPUs let rip on the same piece of memory. It can do great stuff, but it can also go wrong horribly easily and it is infamous for heisenbugs. Message-passing threading, and while it has higher overheads for smaller configurations, it is easier to debug and it scales up much larger (since it's not hard to pass messages to other processes, other computers or even other clusters); indeed, the largest message-passing system in the world is massively parallel and goes by the name of The Internet. Shared memory systems simply can't scale up that large. (As a side note, the apotheosis of a shared memory system came in some of the supercomputers in the '90s, which had very complex memory management hardware to make the model work; these days, supercomputers use message passing because it's far easier to scale that up.)
    --
    "Little does he know, but there is no 'I' in 'Idiot'!"
  91. Erlang doesn't have this problem. (n/t) by toby · · Score: 1

    For example, it has been benchmarked by Ulf Wiger (iirc) with up to 20 million scheduled lightweight concurrent entities ('processes') on one modest box. But that might be because it encourages a lock-free design. :)

    --
    you had me at #!
  92. Re:How about "C++ threads considered harmful"? by SanityInAnarchy · · Score: 1

    I suppose that would work... Erlang isn't quite that, though. That's how a purely-functional language would work, which Erlang isn't.

    Variables may not be changed once bound, but they can be either bound or unbound, and that is a mutable state -- they can change from unbound to bound. If variables were globally accessible in Erlang, I could see race conditions happening.

    The way Erlang avoids locks is by having a shared-nothing architecture. It's all done with message-passing.

    --
    Don't thank God, thank a doctor!
  93. John Ousterhout got it right 13 years ago by fbonnet · · Score: 1

    Why Threads Are A Bad Idea (for most purposes) http://home.pacbell.net/ouster/threads.pdf

  94. Re:Fancy programming languages are NOT the solutio by ulatekh · · Score: 1

    And of course, should you program ever run a multi-processor system, it will fail in all sort of subtile, non-predictive way. E.g., in all cases where a variable has been loaded into a register, but likely there are also cases involving caching to some degree.

    On the aforementioned unnamed game console, that's called a "lightweight sync", and is a processor instruction.

    Don't confuse your lack of knowledge with the lack of an answer.

    --
    "Once we've identified and embraced our sickness, we'll have strength...and that's when we get dangerous." - John Waters
  95. Re:Fancy programming languages are NOT the solutio by EsbenMoseHansen · · Score: 1

    I'm sure it does. But unless that mystery instruction sync's all the processors' caches (and registers, if your compiler decided to put your variable in a register), you will still have these errors. Of course, if I understood you correctly, and the system in question only had one processor, this is not an issue and atomic operations works just fine.

    Threading is always easier on one processor, likewise on one computer unit.

    Don't confuse your lack of knowledge with the lack of an answer.

    No need to get all uptight, it was not a criticism of you.

    --
    Religion is regarded by the common people as true, by the wise as false, and by rulers as useful.
  96. Re:Fancy programming languages are NOT the solutio by ulatekh · · Score: 1

    But unless that mystery instruction sync's all the processors' caches (and registers, if your compiler decided to put your variable in a register), you will still have these errors.

    Mystery instruction? It's well documented.

    Also, anything you need communicated to other threads needs to be put into what C++ would call a "volatile" variable. You can't expect randomly-architected code to just magically work in a multithreaded context.

    Of course, if I understood you correctly, and the system in question only had one processor...

    Where did you get that impression? I clearly called it "asymmetric-multiprocessing".

    At the risk of sounding "uptight", you sound like a very lazy programmer. You don't understand the subject of multithreading, you don't even read what I write, and yet you act as if your opinion has merit.

    --
    "Once we've identified and embraced our sickness, we'll have strength...and that's when we get dangerous." - John Waters
  97. Re:Fancy programming languages are NOT the solutio by EsbenMoseHansen · · Score: 1

    But unless that mystery instruction sync's all the processors' caches (and registers, if your compiler decided to put your variable in a register), you will still have these errors.

    Mystery instruction? It's well documented.

    I was hinting at the fact that we are talking of an unnamed system with unnamed processors. It makes it harder to give a qualified answer

    Also, anything you need communicated to other threads needs to be put into what C++ would call a "volatile" variable. You can't expect randomly-architected code to just magically work in a multithreaded context.

    Volatile won't help you. Volatile just disables some optimisations, and does not sync the caches in the processors - which I admit your mystery instruction might, though I find it unlikely. Try reading volatile considered harmful - I know it is for the linux kernel dev, but it does a fair job of explaining the issues at hand. As an extract

    [...]one must protect shared data structures against unwanted concurrent access, which is very much a different task

    In short, you almost never want to use volatile, unless you are manipulating memory mapped IO through a pointer or similar strange tasks. The key point is that volatile does *not* sync caches in any way.

    At the risk of sounding "uptight", you sound like a very lazy programmer. You don't understand the subject of multithreading, you don't even read what I write, and yet you act as if your opinion has merit.

    lol. You are cute.

    --
    Religion is regarded by the common people as true, by the wise as false, and by rulers as useful.
  98. actually, not by mkcmkc · · Score: 1

    Actually, I was referring to OS processes. Within-process "process-like" threads would also be interesting, and a huge improvement other threading as currently practiced.

    --
    "Not an actor, but he plays one on TV."
    1. Re:actually, not by smallfries · · Score: 1

      Yes I said that. They have horrible overhead for what you are describing. It is much better to replace threads with "process-like" threads as you call them. The theory is quite well developed and has been around for 30+ years. They are a much more productive way to write concurrent code than the horrors that are threads + mutexs.

      --
      Slashdot: where don knuth is an idiot because he cant grasp the awesome power of php
    2. Re:actually, not by mkcmkc · · Score: 1

      They have horrible overhead for what you are describing. For my current project, the overhead appears to be negligible...
      --
      "Not an actor, but he plays one on TV."
    3. Re:actually, not by smallfries · · Score: 1

      I would guess that you are using a small amount of concurrency (2-10 processes?) with large chunks of computation between each context switch. If you start scaling into large amounts of concurrency (1000s processes) and using the concurrency in a more fine-grained manner (shorter computation blocks) then the overhead would probably rise.

      Of course the old adage applies: if it works for you...

      --
      Slashdot: where don knuth is an idiot because he cant grasp the awesome power of php
    4. Re:actually, not by mkcmkc · · Score: 1

      Actually, I'm running my current project with 800+ processes, split across 100 8-way CPUs. I'm lucky in that it's a very parallelizeable problem.

      --
      "Not an actor, but he plays one on TV."
    5. Re:actually, not by smallfries · · Score: 1

      Can I get a account ? :)

      --
      Slashdot: where don knuth is an idiot because he cant grasp the awesome power of php
    6. Re:actually, not by mkcmkc · · Score: 1

      If it was up to me, yes. But in reality I barely have one myself...

      --
      "Not an actor, but he plays one on TV."
  99. Re:Fancy programming languages are NOT the solutio by ulatekh · · Score: 1

    I was hinting at the fact that we are talking of an unnamed system with unnamed processors. It makes it harder to give a qualified answer

    Hmmm, let's see. There are exactly two next-generation game consoles in existence. One is symmetric-multiprocessing, the other is asymmetric-multiprocessing. And you're willing to admit, in public, that you're confused by this?

    I guess it's a stroke of luck that you're too dense to understand how humiliated you should feel.

    --
    "Once we've identified and embraced our sickness, we'll have strength...and that's when we get dangerous." - John Waters
  100. Re:Fancy programming languages are NOT the solutio by EsbenMoseHansen · · Score: 1

    I was hinting at the fact that we are talking of an unnamed system with unnamed processors. It makes it harder to give a qualified answer

    Hmmm, let's see. There are exactly two next-generation game consoles in existence. One is symmetric-multiprocessing, the other is asymmetric-multiprocessing. And you're willing to admit, in public, that you're confused by this?

    Confused? No. But I refuse to guess.

    I guess it's a stroke of luck that you're too dense to understand how humiliated you should feel.

    You are still funny. Do you understand how volatile works now? :p

    Seriously, I am sorry I exposed your ignorance, I know that rubs some people the wrong way. It is just that what you did is --- in general --- such a grave error I thought a warning was appropriate. I am still not speaking of the specific case --- the Cell architecture is not something I have studied in detail, but my understanding was that the was one power-something processor and several non-ram-sharing co-processors, so I think you luck out in your case. It only applies if two cores that do not share cache (typically because they reside on two different chips) attempts to modify the same, cached data.

    --
    Religion is regarded by the common people as true, by the wise as false, and by rulers as useful.
  101. Re:Fancy programming languages are NOT the solutio by ulatekh · · Score: 1

    Confused? No. But I refuse to guess.

    Seems unnecessarily idiosyncratic.

    I am sorry I exposed your ignorance

    Oh really. So if I write to my thread-communication structure through a pointer to volatile memory, do a lightweight sync, then write the flag that tells other threads that the structure is ready for use, then lightweight-sync again, you're telling me that's not valid?

    I hope you know about lightweight-sync; it's part of the PowerPC architecture. That's only been around for nearly twenty years. The hot burning feeling is the realization that your obsolescence is measured in decades.

    --
    "Once we've identified and embraced our sickness, we'll have strength...and that's when we get dangerous." - John Waters
  102. Erlang has other problems, though. by ulatekh · · Score: 1

    Although I'm skeptical, I am reading about Erlang now.

    One problem I see so far is the way messages are passed between processes. Since Erlang is defined to send the message and continue without stopping (and presumably without the possibility of losing the message), that implies dynamic allocations for message queues. That's unacceptable in a limited-memory embedded platform like a video game console. It may be fine in one of Ericcson's telephone switches -- presumably they have more memory and no hard response-time limits (e.g. making framerate).

    --
    "Once we've identified and embraced our sickness, we'll have strength...and that's when we get dangerous." - John Waters
  103. Re:Fancy programming languages are NOT the solutio by EsbenMoseHansen · · Score: 1

    Confused? No. But I refuse to guess.

    Seems unnecessarily idiosyncratic.

    I really don't care what it seems to be to you.

    Oh really. So if I write to my thread-communication structure through a pointer to volatile memory, do a lightweight sync, then write the flag that tells other threads that the structure is ready for use, then lightweight-sync again, you're telling me that's not valid?

    On the condition I gave, no that is not valid. The sync only works on the specific core to provide a barrier to some internal state. But if the memory is cached in two different processors, both will be able to take that "lock" and not discover it.There is nothing magic about this, really. What should prevent this from happening?

    I hope you know about lightweight-sync; it's part of the PowerPC architecture. That's only been around for nearly twenty years. The hot burning feeling is the realization that your obsolescence is measured in decades.

    I have never had to work with that particular processor, so I really don't know why I should have read up on it. My criticism was about your codes portability, not whether it would work on some specific platform.

    --
    Religion is regarded by the common people as true, by the wise as false, and by rulers as useful.
  104. Re:Fancy programming languages are NOT the solutio by ulatekh · · Score: 1

    I really don't care what it seems to be to you.

    I'm like so wounded.

    The sync only works on the specific core to provide a barrier to some internal state. But if the memory is cached in two different processors, both will be able to take that "lock" and not discover it.There is nothing magic about this, really. What should prevent this from happening?

    Because only one thread can write to an instance of that structure at a time? Otherwise I'd need a real semaphore. It's called a "lock-free design", which is a lot more efficient than requiring an operating-system semaphore. Your multithreaded code must thrash the hell out of the operating system. Have you ever profiled any of it?

    I have never had to work with [the PowerPC line of processors], so I really don't know why I should have read up on it.

    General education? To improve the breadth of your knowledge? So that the principles you learn can be applied to other situations? Intellectual cross-training? These things really didn't occur to you?

    You seem to me to be a perfectly normal computer programmer. Problem is, no one ever got anywhere by being normal.

    --
    "Once we've identified and embraced our sickness, we'll have strength...and that's when we get dangerous." - John Waters
  105. Re:Fancy programming languages are NOT the solutio by EsbenMoseHansen · · Score: 1

    Because only one thread can write to an instance of that structure at a time?

    Except this is unlikely to be true. The structure could reside in both CPUs cache, and thus be corrupted. Of course. you would have to be very unlucky on several counts.

    Otherwise I'd need a real semaphore.

    Or similar, sure. That is the only way to be sure, the more's the pity. One reason why multi-threaded code is sometimes slower than single-threaded.

    It's called a "lock-free design", which is a lot more efficient than requiring an operating-system semaphore. Your multithreaded code must thrash the hell out of the operating system. Have you ever profiled any of it?

    I prefer to avoid locks, which works fine for me. But I suspect that my code is very different from what you do, so my methods might not work for you :)

    I have never had to work with [the PowerPC line of processors], so I really don't know why I should have read up on it.

    General education? To improve the breadth of your knowledge? So that the principles you learn can be applied to other situations? Intellectual cross-training? These things really didn't occur to you?

    Learning new things are something I do continually, but obscure processors are quite far down my list :)

    You seem to me to be a perfectly normal computer programmer. Problem is, no one ever got anywhere by being normal.

    Looks like your opinion of me has improved somewhat ;) Anyway, I am a mathematician first, programming is just something I do.

    --
    Religion is regarded by the common people as true, by the wise as false, and by rulers as useful.
  106. Re:Fancy programming languages are NOT the solutio by ulatekh · · Score: 1

    Except this is unlikely to be true. The structure could reside in both CPUs cache, and thus be corrupted.

    Except that this is exactly what lightweight-sync prevents...!

    Learning new things are something I do continually, but obscure processors are quite far down my list :)

    I don't think I've ever heard the PowerPC line of processors described as "obscure".

    I am a mathematician first, programming is just something I do.

    If you don't claim to be a professional computer programmer, I can forgive you for not being this hardcore. The vast majority of my co-workers over the years, though, have no such excuse. ;-)

    --
    "Once we've identified and embraced our sickness, we'll have strength...and that's when we get dangerous." - John Waters