home *** CD-ROM | disk | FTP | other *** search
/ ftp.pasteur.org/FAQ/ / ftp-pasteur-org-FAQ.zip / FAQ / threads-faq / part1
Text File  |  1997-08-24  |  42KB  |  862 lines

  1. Path: senator-bedfellow.mit.edu!bloom-beacon.mit.edu!news-ext.crl.dec.com!decwrl!spool.mu.edu!uwm.edu!news.sprintisp.com!sprintisp!news-west.sprintlink.net!news-peer.sprintlink.net!news-sea-19.sprintlink.net!news-in-west.sprintlink.net!news.sprintlink.net!Sprint!199.60.229.3!newsfeed.direct.ca!newshub1.home.com!news.home.com!news1.best.com!nntp1.ba.best.com!not-for-mail
  2. From: bos@serpentine.com (Bryan O'Sullivan)
  3. Newsgroups: comp.programming.threads,news.answers,comp.answers
  4. Subject: comp.programming.threads FAQ [last mod 97/5/24]
  5. Followup-To: poster
  6. Date: 20 Aug 1997 11:49:24 -0700
  7. Organization: Polymorphous Thaumaturgy
  8. Lines: 845
  9. Approved: threads-faq@serpentine.com, news-answers-request@mit.edu
  10. Message-ID: <87aficzo3v.fsf@serpentine.com>
  11. Reply-To: threads-faq@serpentine.com
  12. NNTP-Posting-Host: organon.serpentine.com
  13. Summary: frequent topics of discussion on the threads programming newsgroup
  14. X-Newsreader: Gnus v5.3/Emacs 19.34
  15. Xref: senator-bedfellow.mit.edu comp.programming.threads:5434 news.answers:110515 comp.answers:27726
  16.  
  17. URL: http://www.serpentine.com/~bos/threads-faq/
  18. Posting-Frequency: monthly
  19. Archive-name: threads-faq/part1
  20. Last-modified: Sat May 24 21:52:47 1997
  21.  
  22. 0.    TABLE OF CONTENTS
  23.                                        
  24. 1.    Answers to frequently asked questions for comp.programming.threads:
  25.       Part 1 of 1
  26. 2.    Introduction
  27. 2.1.  Reader contributions and comments
  28. 2.2.  How to read this FAQ
  29. 2.3.  Acknowledgments and caveats
  30. 3.    What are threads?
  31. 3.1.  Why are threads interesting?
  32. 3.2.  A little history
  33. 4.    What are the main families of threads?
  34. 4.1.  POSIX-style threads
  35. 4.2.  Microsoft-style threads
  36. 4.3.  Others
  37. 5.    Some terminology
  38. 5.1.  (DCE, POSIX, UI) Async safety
  39. 5.2.  Asynchronous and blocking system calls
  40. 5.3.  Context switch
  41. 5.4.  Critical section
  42. 5.5.  Lightweight process
  43. 5.6.  MT safety
  44. 5.7.  Protection boundary
  45. 5.8.  Scheduling
  46. 6.    What are the different kinds of threads?
  47. 6.1.  Architectural differences
  48. 6.2.  Performance differences
  49. 6.3.  Potential problems with functionality
  50. 7.    Where can I find books on threads?
  51. 7.1.  POSIX-style threads
  52. 7.2.  Microsoft-style threads
  53. 7.3.  Books on implementations
  54. 7.4.  The POSIX threads standard
  55. 8.    Where can I obtain training on using threads?
  56. 9.    (Unix) Are there any freely-available threads packages?
  57. 10.   (DCE, POSIX, UI) Why does my threaded program not handle signals
  58.       sensibly?
  59. 11.   (DCE?, POSIX) Why does everyone tell me to avoid asynchronous
  60.       cancellation?
  61. 12.   Why are reentrant library and system call interfaces good?
  62. 12.1. (DCE, POSIX, UI) When should I use thread-safe "_r" library
  63.       calls?
  64. 13.   (POSIX) How can I perform a join on any thread?
  65. 14.   (DCE, UI, POSIX) After I create a certain number of threads, my
  66.       program crashes
  67. 15.   Where can I find POSIX thread benchmarks?
  68. 16.   Does any DBMS vendor provide a thread-safe interface?
  69. 17.   Why is my threaded program running into performance problems?
  70. 18.   What tools will help me to program with threads?
  71. 19.   What operating systems provide threads?
  72. 20.   What about other threads-related software?
  73. 21.   Where can I find other information on threads?
  74. 21.1. Articles appearing in periodicals
  75. 22.   Notice of copyright and permissions
  76.    
  77. 2.    Introduction
  78.                                        
  79.    This posting consists of answers to many of the questions most
  80.    frequently asked and summaries of the topics most frequently covered
  81.    on comp.programming.threads, the Usenet newsgroup for discussion of
  82.    issues in multithreaded programming. The purpose of this posting is to
  83.    circulate existing information, and to avoid rehashing old topics of
  84.    discussion and questions. Please read all parts of this document
  85.    before posting to this newsgroup.
  86.    
  87.    The FAQ is posted monthly to comp.programming.threads, in multiple
  88.    parts. It is also available on the World-Wide Web, at
  89.    <URL: http://www.serpentine.com/~bos/threads-faq>. You may prefer to
  90.    browse the FAQ on the Web rather than on Usenet, as it contains many
  91.    useful hyperlinks (and tables are readable, which is unfortunately not
  92.    the case for the text version).
  93.    
  94. 2.1.  Reader contributions and comments
  95.  
  96.    Your contributions, comments, and corrections are welcomed; mail sent
  97.    to <threads-faq@serpentine.com> will be dealt with as quickly as I can
  98.    manage. Generally, performing a reply or followup to this article from
  99.    within your newsreader should do the Right Thing.
  100.    
  101.    While I am more than happy to include submissions of material for the
  102.    FAQ if they seem appropriate, it would make my life a lot easier if
  103.    such text were proof-read in advance, and kept concise. I don't have
  104.    as much time as I would like to digest 15K text files and summarise
  105.    them in three paragraphs for inclusion here. If you are interested in
  106.    contributing material, please see the to-do list at the end of part 3
  107.    of the FAQ.
  108.    
  109. 2.2.  How to read this FAQ
  110.  
  111.    Some headers in this FAQ are preceded by words in parentheses, such as
  112.    "(POSIX)". This indicates that the sections in question are specific
  113.    to a particular threads family, or to the implementation provided by a
  114.    specific vendor.
  115.    
  116.    Wherever it may not otherwise be obvious that a particular section
  117.    refers only to some families or implementations, you will find one or
  118.    more of the following key words to help you.
  119.    Key Implementation
  120.    DCE OSF/DCE threads (POSIX draft 4)
  121.    OS/2 IBM OS/2 threads
  122.    POSIX POSIX 1003.1c-1995 standard threads
  123.    UI Unix International threads
  124.    Unix Of general relevance to Unix users
  125.    WIN32 Microsoft Win32 API threads
  126.    
  127. 2.3.  Acknowledgments and caveats
  128.  
  129.    Although this FAQ has been the result of a co-operative effort, any
  130.    blame for inaccuracies and/or errors lies entirely with my work. I
  131.    would like to thank the following people for their part in
  132.    contributing to this FAQ:
  133.    Dave Butenhof <butenhof@zko.dec.com>
  134.    Bil Lewis <bil@lambdaCS.com>
  135.    
  136. 3.    What are threads?
  137.                                        
  138.    A thread is an encapsulation of the flow of control in a program. Most
  139.    people are used to writing single-threaded programs - that is,
  140.    programs that only execute one path through their code "at a time".
  141.    Multithreaded programs may have several threads running through
  142.    different code paths "simultaneously".
  143.    
  144.    Why are some phrases above in quotes? In a typical process in which
  145.    multiple threads exist, zero or more threads may actually be running
  146.    at any one time. This depends on the number of CPUs the computer on
  147.    which the process is running, and also on how the threads system is
  148.    implemented. A machine with _n_ CPUs can, intuitively enough, run no
  149.    more than _n_ threads in parallel, but it may give the appearance of
  150.    running many more than _n_ "simultaneously", by sharing the CPUs among
  151.    threads.
  152.    
  153. 3.1.  Why are threads interesting?
  154.  
  155.    A context switch between two threads in a single process is
  156.    _considerably_ cheaper than a context switch between two processes. In
  157.    addition, the fact that all data except for stack and registers are
  158.    shared between threads makes them a natural vehicle for expressing
  159.    tasks that can be broken down into subtasks that can be run
  160.    cooperatively.
  161.    
  162. 3.2.  A little history
  163.  
  164.    If you are interested in reading about the history of threads, see the
  165.    relevant section of the comp.os.research FAQ at
  166.    <URL: http://www.serpentine.com/~bos/os-faq>.
  167.    
  168. 4.    What are the main families of threads?
  169.                                        
  170.    There are two main families of threads:
  171.      * POSIX-style threads, which generally run on Unix systems.
  172.      * Microsoft-style threads, which generally run on PCs.
  173.        
  174.    These families can be further subdivided.
  175.    
  176. 4.1.  POSIX-style threads
  177.  
  178.    This family consists of three subgroups:
  179.      * "Real" POSIX threads, based on the IEEE POSIX 1003.1c-1995 (also
  180.        known as the ISO/IEC 9945-1:1996) standard, part of the ANSI/IEEE
  181.        1003.1, 1996 edition, standard. POSIX implementations are, not
  182.        surprisingly, the emerging standard on Unix systems.
  183.           + POSIX threads are usually referred to as Pthreads.
  184.           + You will often see POSIX threads referred to as POSIX.1c
  185.             threads, since 1003.1c is the section of the POSIX standard
  186.             that deals with threads.
  187.           + You may also see references to draft 10 of POSIX.1c, which
  188.             became the standard.
  189.      * DCE threads are based on draft 4 (an early draft) of the POSIX
  190.        threads standard (which was originally named 1003.4a, and became
  191.        1003.1c upon standardisation). You may find these on some Unix
  192.        implementations.
  193.      * Unix International (UI) threads, also known as Solaris threads,
  194.        are based on the Unix International threads standard (a close
  195.        relative of the POSIX standard). The only major Unix variants that
  196.        support UI threads are Solaris 2, from Sun, and UnixWare 2, from
  197.        SCO.
  198.        
  199.    Both DCE and UI threads are fairly compatible with the POSIX threads
  200.    standard, although converting from either to "real" POSIX threads will
  201.    require a moderate amount of work.
  202.    
  203.    Those few tardy Unix vendors who do not yet ship POSIX threads
  204.    implementations are expected to do so "real soon now". If you are
  205.    developing multithreaded applications from scratch on Unix, you would
  206.    do well to use POSIX threads.
  207.    
  208. 4.2.  Microsoft-style threads
  209.  
  210.    This family consists of two subgroups, both originally developed by
  211.    Microsoft.
  212.      * WIN32 threads are the standard threads on Microsoft Windows 95 and
  213.        Windows NT.
  214.      * OS/2 threads are the standard threads on OS/2, from IBM.
  215.        
  216.    Although both of these were originally implemented by Microsoft, they
  217.    have diverged somewhat over the years. Moving from one to the other
  218.    will require a moderate amount of work.
  219.    
  220. 4.3.  Others
  221.  
  222.    Mach and its derivatives (such as Digital UNIX) provide a threads
  223.    package called C threads. This is not very widely used.
  224.    
  225. 5.    Some terminology
  226.                                        
  227.    The terms here refer to each other in a myriad of ways, so the best
  228.    way to navigate through this section is to read it, and then read it
  229.    again. Don't be afraid to skip forwards or backwards as the need
  230.    appears.
  231.    
  232. 5.1.  (DCE, POSIX, UI) Async safety
  233.  
  234.    Some library routines can be safely called from within signal
  235.    handlers; these are referred to as async-safe. A thread that is
  236.    executing some async-safe code will not deadlock if it is interrupted
  237.    by a signal. If you want to make some of your own code async-safe, you
  238.    should block signals before you obtain any locks.
  239.    
  240. 5.2.  Asynchronous and blocking system calls
  241.  
  242.    Most system calls, whether on Unix or other platforms, block (or
  243.    "suspend") the calling thread until they complete, and continue its
  244.    execution immediately following the call. Some systems also provide
  245.    asynchronous (or _non-blocking_) forms of these calls; the kernel
  246.    notifies the caller through some kind of out-of-band method when such
  247.    a system call has completed.
  248.    
  249.    Asynchronous system calls are generally much harder for the programmer
  250.    to deal with than blocking calls.
  251.    
  252. 5.3.  Context switch
  253.  
  254.    A context switch is the action of switching a CPU between executing
  255.    one thread and another (or transferring control between them). This
  256.    may involve crossing one or more protection boundary.
  257.    
  258. 5.4.  Critical section
  259.  
  260.    A critical section of code is one in which data that may be accessed
  261.    by other threads are inconsistent. At a higher level, a critical
  262.    section can be viewed as a section of code in which a guarantee you
  263.    make to other threads about the state of some data may not be true.
  264.    
  265.    If other threads can access these data during a critical section, your
  266.    program may not behave correctly. This may cause it to crash, lock up,
  267.    produce incorrect results, or do just about any other unpleasant thing
  268.    you care to imagine.
  269.    
  270.    Other threads are generally denied access to inconsistent data during
  271.    a critical section (usually through use of locks). If some of your
  272.    critical sections are too long, however, it may result in your code
  273.    performing poorly.
  274.    
  275. 5.5.  Lightweight process
  276.  
  277.    A lightweight process (also known in some implementations,
  278.    confusingly, as a _kernel thread_) is a schedulable entity that the
  279.    kernel is aware of. On most systems, it consists of some execution
  280.    context and some accounting information (i.e. much less than a
  281.    full-blown process).
  282.    
  283.    Several operating systems allow lightweight processes to be "bound" to
  284.    particular CPUs; this guarantees that those threads will only execute
  285.    on the specified CPUs.
  286.    
  287. 5.6.  MT safety
  288.  
  289.    If some piece of code is described as MT-safe, this indicates that it
  290.    can be used safely within a multithreaded program, _and_ that it
  291.    supports a "reasonable" level of concurrency. This isn't very
  292.    interesting; what you, as a programmer using threads, need to worry
  293.    about is code that is _not_ MT-safe. MT-unsafe code may use global
  294.    and/or static data. If you need to call MT-unsafe code from within a
  295.    multithreaded program, you may need to go to some effort to ensure
  296.    that only one thread calls that code at any time.
  297.    
  298.    Wrapping a global lock around MT-unsafe code will generally let you
  299.    call it from within a multithreaded program, but since this does not
  300.    permit concurrent access to that code, it is not considered to make it
  301.    MT-safe.
  302.    
  303.    If you are trying to write MT-safe code using POSIX threads, you need
  304.    to worry about a few issues such as dealing correctly with locks
  305.    across calls to fork(2) (if you are wondering what to do, read about
  306.    the pthread_atfork(3) library call).
  307.    
  308. 5.7.  Protection boundary
  309.  
  310.    A protection boundary protects one software subsystem on a computer
  311.    from another, in such a way that only data that is explicitly shared
  312.    across such a boundary is accessible to the entities on both sides. In
  313.    general, all code within a protection boundary will have access to all
  314.    data within that boundary.
  315.    
  316.    The canonical example of a protection boundary on most modern systems
  317.    is that between processes and the kernel. The kernel is protected from
  318.    processes, so that they can only examine or change its internal state
  319.    in certain strictly-defined ways.
  320.    
  321.    Protection boundaries also exist between individual processes on most
  322.    modern systems. This prevents one buggy or malicious process from
  323.    wreaking havoc on others.
  324.    
  325.    Why are protection boundaries interesting? Because transferring
  326.    control across them is expensive; it takes a lot of time and work.
  327.    
  328. 5.8.  Scheduling
  329.  
  330.    Scheduling involves deciding what thread should execute next on a
  331.    particular CPU. It is usually also taken as involving the context
  332.    switch to that thread.
  333.    
  334. 6.    What are the different kinds of threads?
  335.                                        
  336.    There are two main kinds of threads implementations:
  337.      * User-space threads, and
  338.      * Kernel-supported threads.
  339.        
  340.    There are several sets of differences between these different threads
  341.    implementations.
  342.    
  343. 6.1.  Architectural differences
  344.  
  345.    User-space threads live without any support from the kernel; they
  346.    maintain all of their state in user space. Since the kernel does not
  347.    know about them, they cannot be scheduled to run on multiple
  348.    processors in parallel.
  349.    
  350.    Kernel-supported threads fall into two classes.
  351.      * In a "pure" kernel-supported system, the kernel is responsible for
  352.        scheduling all threads.
  353.      * Systems in which the kernel cooperates with a user-level library
  354.        to do scheduling are known as _two-level_, or _hybrid_, systems.
  355.        Typically, the kernel schedules LWPs, and the user-level library
  356.        schedules threads onto LWPs.
  357.        
  358.    Because of its performance problems (caused by the need to cross the
  359.    user/kernel protection boundary twice for _every_ thread context
  360.    switch), the former class has fewer members than does the latter (at
  361.    least on Unix variants). Both classes allow threads to be run across
  362.    multiple processors in parallel.
  363.    
  364. 6.2.  Performance differences
  365.  
  366.    In terms of context switch time, user-space threads are the fastest,
  367.    with two-level threads coming next (all other things being equal).
  368.    However, if you have a multiprocessor, user-level threads can only be
  369.    run on a single CPU, while both two-level and pure kernel-supported
  370.    threads can be run on multiple CPUs simultaneously.
  371.    
  372. 6.3.  Potential problems with functionality
  373.  
  374.    Because the kernel does not know about user threads, there is a danger
  375.    that ordinary blocking system calls will block the entire process
  376.    (this is _bad_) rather than just the calling thread. This means that
  377.    user-space threads libraries need to jump through hoops in order to
  378.    provide "blocking" system calls that don't block the entire process.
  379.    
  380.    This problem also exists with two-level kernel-supported threads,
  381.    though it is not as acute as for user-level threads. What usually
  382.    happens here is that system calls block entire LWPs. This means that
  383.    if more threads exist than do LWPs and all of the LWPs are blocked in
  384.    system calls, then other threads that could potentially make forward
  385.    progress are prevented from doing so.
  386.    
  387.    The Solaris threads library provides a reasonable solution to this
  388.    problem. If the kernel notices that all LWPs in a process are blocked,
  389.    it sends a signal to the process. This signal is caught by the
  390.    user-level threads library, which can create another LWP so that the
  391.    process will continue to make progress.
  392.    
  393. 7.    Where can I find books on threads?
  394.                                        
  395.    There are several books available on programming with threads, with
  396.    more due out in the near future. Note also that the programmer's
  397.    manuals that come with most systems that provide threads packages will
  398.    have sections on using those threads packages.
  399.    
  400. 7.1.  POSIX-style threads
  401.  
  402.    David R. Butenhof, _Programming with POSIX Threads_. Addison-Wesley,
  403.           ISBN 0-201-63392-2.
  404.           This book gives a comprehensive and well-structured overview of
  405.           programming with POSIX threads, and is a good text for the
  406.           working programming to work from. Detailed examples and
  407.           discussions abound.
  408.           
  409.    Steve Kleiman, Devang Shah and Bart Smaalders, _Programming With
  410.           Threads_. SunSoft Press, ISBN 0-13-172389-8.
  411.           <URL: http://www.sun.com/smi/ssoftpress/books/Kleiman/Kleiman.h
  412.           tml>
  413.           This book goes into considerably greater depth than the other
  414.           SunSoft Press offering (see below), and is also recommended for
  415.           the working programmer who expects to deal with threads on a
  416.           day-to-day basis. It includes many detailed examples.
  417.           
  418.    Bil Lewis and Daniel J. Berg, _Threads Primer_. SunSoft Press,
  419.           ISBN 0-13-443698-9.
  420.           <URL: http://www.sun.com/smi/ssoftpress/books/Lewis/Lewis.html>
  421.           
  422.           This is a good introduction to programming with threads for
  423.           programmers and managers. It concentrates on UI and POSIX
  424.           threads, but also covers use of OS/2 and WIN32 threads.
  425.           
  426.    Charles J. Northrup, _Programming With Unix Threads_. John Wiley &
  427.           Sons, ISBN 0-471-13751-0.
  428.           <URL: http://www.wiley.com/compbooks/catalog/14/13751-0.html>
  429.           This book details the UI threads interface, focusing mostly on
  430.           the Unixware implementation. This is an introductory book.
  431.           
  432. 7.2.  Microsoft-style threads
  433.  
  434.    Jim Beveridge, Robert Wiener, _Multithreading Applications in Win32_.
  435.           Addison-Wesley, ISBN 0-201-44234-5.
  436.           <URL: http://www.aw.com/devpress/titles/44234.html>.
  437.           Seasoned Win32 programmers, neophytes, and programmers being
  438.           dragged kicking and screaming from the Unix world are all
  439.           likely to find this book a useful resource. It doubles as
  440.           primer and reference on writing and debugging robust
  441.           multithreaded code, and provides a thorough exposition on the
  442.           subject.
  443.           
  444.    Len Dorfman, Marc J. Neuberger, _Effective Multithreading with OS/2_.
  445.           Publisher and ISBN unknown.
  446.           This book covers the OS/2 threads API and contains many
  447.           examples, but doesn't have much by way of concepts.
  448.           
  449.    Thuan Q. Pham, Pankaj K. Garg, _Multithreaded Programming with
  450.           Windows NT_. Prentice Hall, ISBN 0-131-20643-5.
  451.           <URL: http://www.prenhall.com/013/120642/12064-2.html>
  452.           Not surprisingly, this book focuses on WIN32 threads, but it
  453.           also mentions other libraries in passing. It also deals with
  454.           some relatively advanced topics, and has a thorough
  455.           bibliography.
  456.           
  457. 7.3.  Books on implementations
  458.  
  459.    If you are interested in how modern operating systems support threads
  460.    and multiprocessors, there are a few excellent books available that
  461.    may be of interest to you.
  462.    
  463.    Curt Schimmel, _Unix Systems for Modern Architectures_.
  464.           Addison-Wesley, ISBN 0-201-63338-8.
  465.           <URL: http://www.aw.com/cp/schimmel.html>
  466.           This book gives a lucid account of the work needed to get Unix
  467.           (or, for that matter, more or less anything else) working on a
  468.           modern system that incorporates multiple processors, each with
  469.           its own cache. While it has some overlap with the Vahalia book
  470.           (see below), it has a smaller scope, and thus deals with shared
  471.           topics in more detail.
  472.           
  473.    Uresh Vahalia, _Unix Internals: the New Frontiers_. Prentice Hall,
  474.           ISBN 0-13-101908-2.
  475.           <URL: http://www.prenhall.com/013/101907/10190-7.html>
  476.           This is the best kernel internals book currently available. It
  477.           deals extensively with building multithreaded kernels,
  478.           implementing LWPs, and scheduling on multiprocessors. Given a
  479.           choice, I would buy _both_ this and the Schimmel book.
  480.           
  481.    Ben Catanzaro, _Multiprocessor System Architectures_. SunSoft Press,
  482.           ISBN 0-13-089137-1.
  483.           <URL: http://www.sun.com/smi/ssoftpress/books/Catanzaro/Catanza
  484.           ro.html>
  485.           I don't know much about this book, but it deals with both the
  486.           hardware and software (kernel and user) architectures used to
  487.           put together modern multiprocessor systems.
  488.           
  489. 7.4.  The POSIX threads standard
  490.  
  491.    To order ISO/IEC standard 9945-1:1996, which is also known as
  492.    ANSI/IEEE POSIX 1003.1-1995 (and includes 1003.1c, the part that deals
  493.    with threads), you can call +1-908-981-1393. The document reference
  494.    number in the IEEE publications catalogue is SH 94352-NYF, and the
  495.    price to US customers is $120 (shipping overseas costs extra).
  496.    
  497.    Unless you are implementing a POSIX threads package, you should not
  498.    ever need to look at the POSIX threads standard. It is the last place
  499.    you should look if you wish to learn about threads!
  500.    
  501.    Neither IEEE nor ISO makes standards available for free; please do not
  502.    ask whether the POSIX threads standard is available on the Web. It
  503.    isn't.
  504.    
  505. 8.    Where can I obtain training on using threads?
  506.                                        
  507.    Organisation Contact Description
  508.    Sun Microsystems <training_seats@Sun.COM>
  509.    +1-408-276-3630 Classes at Sun and on-site classes
  510.    Lambda Computer Science
  511.    (Bil Lewis) <URL: http://www.lambdaCS.com>
  512.    +1-415-328-8952 Seminars and on-site classes
  513.    Phoenix Technologies
  514.    (Chris Crenshaw) <phnxtech@attmail.com>
  515.    +1-908-286-2118
  516.    Marc Staveley <marc@staveley.com>
  517.    
  518. 9.    (Unix) Are there any freely-available threads packages?
  519.                                        
  520.      * Xavier Leroy <xleroy@inria.fr> has written a POSIX threads
  521.        implementation for Linux 2.x that uses pure kernel-supported
  522.        threads. While the package is currently in alpha testing, it is
  523.        allegedly very stable. For more information, see
  524.        <URL: http://pauillac.inria.fr/~xleroy/linuxthreads>.
  525.      * Michael T. Peterson <mtp@big.aa.net> has written a user-space
  526.        POSIX and DCE threads package for Intel-based Linux systems; it is
  527.        called PCthreads. See <URL: http://www.aa.net/~mtp/PCthreads.html>
  528.        for more information.
  529.      * Christopher Provenzano <proven@mit.edu> has written a fairly
  530.        portable implementation of draft 8 of the POSIX threads standard.
  531.        See <URL: http://www.mit.edu:8001/people/proven/pthreads.html> for
  532.        further details. _Note_: as far as I can see, development of this
  533.        library has halted (at least temporarily), and it still contains
  534.        many serious bugs.
  535.      * Georgia Tech's OS group has a fairly portable user-level threads
  536.        implementation of the Mach C threads package. It is called
  537.        Cthreads, and can be found at
  538.        <URL: ftp://ftp.cc.gatech.edu/pub/groups/systems/Falcon/cthreads_d
  539.        istribution.tar.gz>.
  540.      * Frank Mⁿller, of the POSIX / Ada-Runtime Project (PART) has made
  541.        available an implementation of draft 6 of the POSIX 1003.4a
  542.        Pthreads specification, which runs under SunOS 4, Solaris 2.x,
  543.        SCO Unix, FreeBSD and Linux. For more information, see
  544.        <URL: file://ftp.cs.fsu.edu/pub/PART/PTHREADS/pthreads_ANNOUNCE>.
  545.      * Elan Feingold has written a threads package called ethreads; I
  546.        don't know anything about it, other than that it is available from
  547.        <URL: ftp://frmap711.mathp7.jussieu.fr/pub/scratch/rideau/misc/thr
  548.        eads/ethreads/ethreads.tgz>.
  549.      * QuickThreads is a toolkit for building threads packages, written
  550.        by David Keppel <pardo@cs.washington.edu>. It is available from
  551.        <URL: ftp://ftp.cs.washington.edu/pub/qt-001.tar.Z>, with an
  552.        accompanying tech report at
  553.        <URL: ftp://ftp.cs.washington.edu/tr/1993/05/UW-CSE-93-05-06.PS.Z>
  554.        . The code as distributed includes ports for the Alpha, x86,
  555.        88000, MIPS, SPARC, VAX, and KSR1.
  556.        
  557. 10.   (DCE, POSIX, UI) Why does my threaded program not handle signals sensibly?
  558.                                        
  559.    Signals and threads do not mix well. A lot of programmers start out by
  560.    writing their code under the mistaken assumption that they can set a
  561.    signal handler for each thread; this is not the way things work. You
  562.    can _block_ or _unblock_ signals on a thread-by-thread basis, but this
  563.    is not the same thing.
  564.    
  565.    When it comes to dealing with signals, the best thing you can do is
  566.    create a thread whose sole purpose is to handle signals for the entire
  567.    process. This thread should loop calling sigwait(2); this allows it to
  568.    deal with signals synchronously. You should also make sure that all
  569.    threads (_including_ the one that calls sigwait) have the signals you
  570.    are interested in handling blocked. Handling signals synchronously in
  571.    this way greatly simplifies things.
  572.    
  573.    Note, also, that sending signals to other threads within your own
  574.    process is not a friendly thing to do, unless you are careful with
  575.    signal masks. For an explanation, see the section on asynchronous
  576.    cancellation.
  577.    
  578.    Finally, using sigwait and installing signals handlers for the signals
  579.    you are sigwaiting for is a bad idea.
  580.    
  581. 11.   (DCE?, POSIX) Why does everyone tell me to avoid asynchronous cancellation?
  582.                                        
  583.    Asynchronous cancellation of threads is, in general, evil. The reason
  584.    for this is that it is usually (very) difficult to guarantee that the
  585.    recipient of an asynchronous cancellation request will not be in a
  586.    critical section. If a thread should die in the middle of a critical
  587.    section, this will very likely cause your program to misbehave.
  588.    
  589.    Code that can deal sensibly with asynchronous cancellation requests is
  590.    _not_ referred to as async-safe; that means something else (see the
  591.    terminology section of the FAQ). You won't see much code around that
  592.    handles asynchronous cancellation requests properly, and you shouldn't
  593.    try write any of your own unless you have compelling reasons to do so.
  594.    Deferred cancellation is your friend.
  595.    
  596. 12.   Why are reentrant library and system call interfaces good?
  597.                                        
  598.    There are two approaches to providing system calls and library
  599.    interfaces that will work with multithreaded programs. One is to
  600.    simply wrap all the appropriate code with mutexes, thereby
  601.    guaranteeing that only one thread will execute any such routine at a
  602.    time.
  603.    
  604.    While this approach mostly works, it provides terrible performance.
  605.    For functions that maintain state across multiple invocations
  606.    (e.g. strtok() and friends), this approach simply doesn't work at all,
  607.    hence the existence of "_r" interfaces on many Unix systems (see
  608.    below).
  609.    
  610.    A better solution is to ensure that library calls can safely be
  611.    performed by multiple threads at once.
  612.    
  613. 12.1. (DCE, POSIX, UI) When should I use thread-safe "_r" library calls?
  614.  
  615.    If your system provides threads, it will probably provide a set of
  616.    thread-safe variants of standard C library routines. A small number of
  617.    these are mandated by the POSIX standard, and many Unix vendors
  618.    provide their own useful supersets, including functions such as
  619.    gethostbyname_r().
  620.    
  621.    Unfortunately, the supersets that different vendors support do not
  622.    necessarily overlap, so you can only _safely_ use the standard
  623.    POSIX-mandated functions. The thread-safe routines are conceptually
  624.    "cleaner" than their stateful counterparts, though, so it is good
  625.    practice to use them wherever and whenever you can.
  626.    
  627. 13.   (POSIX) How can I perform a join on any thread?
  628.                                        
  629.    UI threads allow programmers to join on any thread that happens to
  630.    terminate by passing the appropriate argument to thr_join(). This is
  631.    not possible under POSIX and, yes, there is a rationale behind the
  632.    absence of this feature.
  633.    
  634.    Unix programmers are used to being able to call wait() in such a way
  635.    that it will return when "any" process exits, but expecting this to
  636.    work for threads can cause confusion for programmers trying to use
  637.    threads. The important thing to note here is that Unix processes are
  638.    based around a notion of parent and child; this is a notion that is
  639.    _not_ present in most threads systems. Since threads don't contain
  640.    this notion, joining on "any" thread could have the undesirable effect
  641.    of having the join return once a completely unrelated thread happened
  642.    to exit.
  643.    
  644.    In many (perhaps even most) threaded applications, you do not want to
  645.    be able to join with any thread in your process. Consider, for
  646.    example, a library call that one of your threads might make, which in
  647.    its turn might start a few threads and try to join on them. If another
  648.    of your threads, joining on "any" thread, happened to join on one of
  649.    the library call's threads, that would lead to incorrect program
  650.    behaviour.
  651.    
  652.    If you want to be able to join on any thread so that, for example, you
  653.    can keep track of the number of running threads, you can achieve the
  654.    same functionality by starting detached threads and having them
  655.    decrememnt a (suitably locked, of course) counter as they exit.
  656.    
  657. 14.   (DCE, UI, POSIX) After I create a certain number of threads, my program
  658.                                     crashes
  659.                                        
  660.    By default, threads are created non-detached. You need to perform a
  661.    join on each non-detached thread, or else storage will never be freed
  662.    up when they exit. As an alternative, you can create detached threads,
  663.    for which storage will be freed as soon as they exit. This latter
  664.    approach is generally better; you shouldn't create non-detached
  665.    threads unless you explicitly need to know when or if they exit.
  666.    
  667. 15.   Where can I find POSIX thread benchmarks?
  668.                                        
  669.    I do not know of any benchmarks.
  670.    
  671. 16.   Does any DBMS vendor provide a thread-safe interface?
  672.                                        
  673.    Oracle 7.3 and above provide thread-safe database client interfaces,
  674.    as do Sybase System 11.1 and above, and Informix ESQL 7 and above.
  675.    
  676.    If you are still using an older release of any of these products, it
  677.    is possible to hack together a set of intermediate thread-safe
  678.    interfaces to your database if you really need it, but this requires a
  679.    moderately large amount of work.
  680.    
  681. 17.   Why is my threaded program running into performance problems?
  682.                                        
  683.    There are many possible causes for performance problems in
  684.    multithreaded programs. Given the scope for error, all I can do is
  685.    detail a few common pitfalls briefly, and point you at the section of
  686.    this FAQ on books about multithreaded programming.
  687.      * You can probably discount the performance of the threads package
  688.        you are using almost straight away, unless it is a user-level
  689.        package. If so, you may want to try to find out whether your whole
  690.        process is blocking when you execute certain system calls.
  691.        Otherwise, you should look at your own code unless you have a very
  692.        strong reason for believing that there may be a problem with your
  693.        threads package.
  694.      * Look at the granularity of your locks. If a single lock protects
  695.        too much data for which there is contention, you will needlessly
  696.        serialise your code. On the other hand, if your locks protect very
  697.        small amounts of data, you will spend too much time obtaining and
  698.        releasing locks. If your vendor is worth their salt, they will
  699.        have a set of tools available that allow you to profile your
  700.        program's behaviour and look for areas of high contention for
  701.        locks. Tools of this kind are invaluable.
  702.        
  703. 18.   What tools will help me to program with threads?
  704.                                        
  705.      * The TNF Tools are a set of extensible tools that allow users to
  706.        gather and analyse trace information from the Solaris kernel and
  707.        from user processes and threads. They can be used to correlate
  708.        user and kernel thread activity, and also to determine such things
  709.        as lock hold times. They are available for free from Sun; for more
  710.        information, see
  711.        <URL: http://opcom.sun.ca/toolpages/tnftools.html>.
  712.      * The debugger that comes with the DevPro compiler set from Sun
  713.        understands threads.
  714.      * GDB nominally understands threads, but only supports them (and in
  715.        a flaky way) under some versions of Irix and a few other systems
  716.        (mostly embedded machines).
  717.        
  718. 19.   What operating systems provide threads?
  719.                                        
  720.    Vendor OS version Threads model POSIX API Notes
  721.    Digital Digital UNIX 4.0 mixed D4, 1c
  722.    Digital UNIX 3.2 kernel / bound D4
  723.    OpenVMS 7.0 (Alpha) see note 1 D4, 1c user model without patch kit
  724.    OpenVMS 7.0 (VAX) user D4, 1c
  725.    OpenVMS 6.2 user D4
  726.    HP HP/UX 10.20 _?_ _?_ not yet announced
  727.    HP/UX 10.10 user D4
  728.    IBM AIX 4.1 & 4.2 kernel D4, D7
  729.    AIX 3.5.x user DCE
  730.    OS/2 kernel DCE
  731.    Linux Linux 1.2.13 and above user / kernel 1c, DCE see free
  732.    implementations for several packages
  733.    Linux 2.x kernel _n/a_ clone() interface
  734.    Microsoft Windows NT & 95 kernel DCE DCE kits layer on top of WIN32
  735.    threads
  736.    SGI Irix 6.2 mixed see note 2 sproc() is still kernel / bound
  737.    Irix 6.1 kernel / bound _n/a_ sproc() interface only
  738.    Sun Solaris 2.5 and above mixed / system / bound 1c
  739.    Solaris 2.4 mixed / system / bound D8 available from Sun only upon
  740.    request
  741.    Solaris 2.x mixed / system / bound _n/a_ UI threads supported across
  742.    all releases
  743.    SunOS 4.x user _n/a_ LWP only
  744.    Threads model Meaning
  745.    user
  746.    a purely user-level threads system, with threads multiplexed atop a
  747.    "traditional" Unix-style process
  748.    kernel
  749.    threads are "kernel entities" with no context switches taking place in
  750.    user mode
  751.    
  752.    / bound a thread may be explicitly bound to a particular processor
  753.    mixed
  754.    a mixed-mode scheduler where user threads are multiplexed across some
  755.    number of LWPs
  756.    
  757.    / system threads have "system" contention scope (a user thread may be
  758.    permanently bound to an LWP)
  759.    
  760.    / bound an LWP may be permanently bound to a particular processor
  761.    API Meaning
  762.    _n/a_ no POSIX threads API provided
  763.    1c conforms to the POSIX 1003.1c-1995 threads API
  764.    DCE POSIX 1003.4a draft 4 API is available as part of the OSF DCE kit
  765.    for the platform
  766.    D4 DCE threads (or something similar) is bundled with the system
  767.    D7 POSIX 1003.4a draft 7 API (similar to the final 1003.1c standard,
  768.    but substantially different in some details)
  769.    D8 POSIX 1003.4a draft 8 API (identical in most respects to the
  770.    1003.1c standard, but with a few "gotchas")
  771. 1.    OpenVMS 7.0 for Alpha shipped with kernel threads support disabled
  772.        by default. The "mixed" threads model can be turned on by setting
  773.        the MULTITHREAD sysgen parameter. With patch kit, the "mixed" or
  774.        "user" model is determined by the main program binary (i.e. via
  775.        the linker or the threadcp qualifier) in addition to MULTITHREAD.
  776. 2.    SGI ships the POSIX 1003.1c API as a patch for Irix 6.2, but it
  777.        will be bundled with future revisions of the OS.
  778.        
  779. 20.   What about other threads-related software?
  780.                                        
  781.      * Douglas C. Schmidt <schmidt@cs.wustl.edu> has written a package
  782.        called ACE (_Adaptive Communication Environment_). ACE supports
  783.        multithreading on Unix and WIN32 platforms, and integrates popular
  784.        IPC mechanisms (sockets, RPC, System V IPC) and a host of other
  785.        features that C++ programmers will find useful. For details, see
  786.        <URL: http://www.cs.wustl.edu/~schmidt/ACE.html>.
  787.        
  788. 21.   Where can I find other information on threads?
  789.                                        
  790.      * The most comprehensive collection of threads-related information
  791.        on the Web is at Sun's threads page, at
  792.        <URL: http://www.sun.com/sunsoft/Products/Developer-products/sig/t
  793.        hreads>.
  794.      * IBM has a thorough treatment of AIX 4.1 threads (based on POSIX
  795.        draft 7) at
  796.        <URL: http://developer.austin.ibm.com/sdp/library/ref/about4.1/df4
  797.        threa.html>.
  798.      * Digital has a brief overview of threads in Digital UNIX at
  799.        <URL: http://www.unix.digital.com/unix/smp>.
  800.      * A bibliography on threads is available at
  801.        <URL: http://liinwww.ira.uka.de/bibliography/Os/threads.html>.
  802.      * Tom Wagner <wagner@cs.umass.edu> and Don Towsley have written an
  803.        introductory tutorial on programming with POSIX threads at
  804.        <URL: http://centaurus.cs.umass.edu/~wagner/threads_html/tutorial.
  805.        html>
  806.        
  807. 21.1. Articles appearing in periodicals
  808.  
  809.      * An introduction to programming with threads, at
  810.        <URL: http://www.sun.com/sunworldonline/swol-02-1996/swol-02-threa
  811.        ds.html>, from SunWorld Online's February 1996 issue
  812.      * An introduction to programming with threads, at
  813.        <URL: http://developer.austin.ibm.com/sdp/library/aixpert/nov94/ai
  814.        xpert_nov94_intrmult.html>, from AIXpert Magazine's November 1994
  815.        issue
  816.      * Porting DCE threads to AIX 4.1 (POSIX draft 7), at
  817.        <URL: http://www.developer.ibm.com/sdp/library/aixpert/aug94/aixpe
  818.        rt_aug94_PTHREADS.html>, from AIXpert Magazine's August 1994 issue
  819.      * A less thorough introduction to programming with threads, at
  820.        <URL: http://developer.austin.ibm.com/sdp/library/aixpert/aug95/ai
  821.        xpert_aug95_thread.html>, from AIXpert Magazine's August 1995
  822.        issue
  823.      * Using signals with POSIX threads, at
  824.        <URL: http://developer.austin.ibm.com/sdp/library/aixpert/aug95/ai
  825.        xpert_aug95_signal.html>, from AIXpert Magazine's August 1995
  826.        issue
  827.        
  828. 22.   Notice of copyright and permissions
  829.                                        
  830.    Answers to Frequently Asked Questions for comp.programming.threads
  831.    (hereafter referred to as These Articles) are Copyright ⌐ 1996 and
  832.    1997 by Bryan O'Sullivan (hereafter referred to as The Author).
  833.    
  834.    These Documents are provided "as is". The information in them is not
  835.    warranted to be correct; you use it at your own risk. The Author makes
  836.    _no representation or warranty_ as to the suitability of the
  837.    information in These Documents, either express or implied, including
  838.    but not limited to the implied warranties of fitness for a particular
  839.    purpose or non-infringement. The Author shall not be liable for any
  840.    damages suffered as a result of using information distributed in These
  841.    Documents or any derivatives.
  842.    
  843.    These Documents may be reproduced and distributed in whole or in part,
  844.    subject to the following conditions:
  845.      * This copyright and permission notice must be retained on all
  846.        complete or partial copies of These Articles.
  847.      * These Articles may be copied or distributed in part or in full for
  848.        personal or educational use. Any translation, derivative work, or
  849.        copies made for other purposes must be approved by the copyright
  850.        holder before distribution, unless otherwise stated.
  851.      * If you distribute These Articles, instructions for obtaining the
  852.        complete current versions of them free or at cost price must be
  853.        included. Redistributors must make reasonable efforts to maintain
  854.        current copies of These Articles.
  855.        
  856.    Exceptions to these rules may be granted, and I shall be happy to
  857.    answer any questions about this copyright notice - write to Bryan
  858.    O'Sullivan, PO Box 62215, Sunnyvale, CA 94088-2215, USA or email
  859.    <bos@serpentine.com>. These restrictions are here to protect the
  860.    contributors, not to restrict you as educators, professionals and
  861.    learners.
  862.