⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 commoncpp2.texi

📁 贡献一份commoncpp2,有兴趣的可以研究一下
💻 TEXI
📖 第 1 页 / 共 4 页
字号:
may require within the constructor of your derived thread class, andto purge or restore any allocated resources in the destructor.  Inmost cases, the destructor will be executed after the thread hasterminated, and hence will execute within the context of the threadthat requested a join rather than in the context of the thread that isbeing terminated.  Most destructors in derived thread classes shouldfirst call terminate() to make sure the thread has stopped runningbefore releasing resources.@cindex thread joinA GNU Common C++ thread is normally canceled by deleting the threadobject.  The process of deletion invokes the thread's destructor, andthe destructor will then perform a "join" against the thread using theterminate() function.  This behavior is not always desirable since thethread may block itself from cancellation and block the current"delete" operation from completing.  One can alternately invoketerminate() directly before deleting a thread object.@findex Thread::final@findex operator new@cindex detached threadWhen a given GNU Common C++ thread exits on it's own through it'srun() method, a "final" method will be called.  This Final method willbe called while the thread is "detached".  If a thread object isconstructed through a "new" operator, it's final method can be used to"self delete" when done, and allows an independent thread to constructand remove itself autonomously.@findex getThread@cindex pthread_selfA special global function, getThread(), is provided to identify thethread object that represents the current execution context you arerunning under.  This is sometimes needed to deliver signals to thecorrect thread.  Since all thread manipulation should be done throughthe GNU Common C++ (base) thread class itself, this provides the samefunctionality as things like "pthread_self" for GNU Common C++.GNU Common C++ threads are often aggregated into other classes toprovide services that are "managed" from or operate within the contextof a thread, even within the GNU Common C++ framework itself.  A goodexample of this is the TCPSession class, which essentially is acombination of a TCP client connection and a separate thread the usercan define by deriving a class with a Run() method to handle theconnected service.  This aggregation logically connects the successfulallocation of a given resource with the construction of a thread tomanage and perform operations for said resource.Threads are also used in "service pools".  In GNU Common C++, aservice pool is one or more threads that are used to manage a set ofresources.  While GNU Common C++ does not provide a direct "pool"class, it does provide a model for their implementation, usually byconstructing an array of thread "service" objects, each of which canthen be assigned the next new instance of a given resource in turn oralgorithmically.@findex Thread::signal@findex Thread::onDisconnect@findex Thread::onHangup@cindex SIGPIPE@cindex SIGHUPThreads have signal handlers associated with them.  Several signaltypes are "predefined" and have special meaning.  All signal handlersare defined as virtual member functions of the Thread class which arecalled when a specific signal is received for a given thread.  The"SIGPIPE" event is defined as a "onDisconnect" event since it's normallyassociated with a socket disconnecting or broken fifo.  The onHangup()method is associated with the SIGHUP signal.  All other signals arehandled through the more generic signal().Incidently, unlike Posix, the win32 API has no concept of signals, andcertainly no means to define or deliver signals on a per-thread basis.For this reason, no signal handling is supported or emulated in thewin32 implementation of GNU Common C++ at this time.@tindex TCPStream@tindex TCPSessionIn addition to TCPStream, there is a TCPSession class which combines athread with a TCPStream object.  The assumption made by TCPSession isthat one will service each TCP connection with a separate thread, andthis makes sense for systems where extended connections may bemaintained and complex protocols are being used over TCP.@c -----------------------------------------------------------------------@node Synchronization@section Synchronization@cindex SynchronizationSynchronization objects are needed when a single object can bepotentially manipulated by more than one thread (execution) contextconcurrently.  GNU Common C++ provides a number of specialized classesand objects that can be used to synchronize threads.@tindex MutexOne of the most basic GNU Common C++ synchronization object is theMutex class.  A Mutex only allows one thread to continue execution ata given time over a specific section of code.  Mutex's have a enterand leave method; only one thread can continue from the Enter untilthe Leave is called.  The next thread waiting can then get through.Mutex's are also known as "CRITICAL SECTIONS" in win32-speak.The GNU Common C++ mutex is presumed to support recursive locking.This was deemed essential because a mutex might be used to blockindividual file requests in say, a database, but the same mutex mightbe needed to block a whole series of database updates that compose a"transaction" for one thread to complete together without having towrite alternate non-locking member functions to invoke for each partof a transaction.Strangely enough, the original pthread draft standard does notdirectly support recursive mutexes.  In fact this is the most common"NP" extension for most pthread implementations.  GNU Common C++emulates recursive mutex behavior when the target platform does notdirectly support it.@tindex ThreadLockIn addition to the Mutex, GNU Common C++ supports a rwlock class(ThreadLock).  This implements the X/Open recommended "rwlock".  Onsystems which do not support rwlock's, the behavior is emulated with aMutex; however, the advantage of a rwlock over a mutex is thenentirely lost.  There has been some suggested clever hacks for"emulating" the behavior of a rwlock with a pair of mutexes and asemaphore, and one of these will be adapted for GNU Common C++ in thefuture for platforms that do not support rwlock's directly.@tindex SemaphoreGNU Common C++ also supports "semaphores".  Semaphores are typicallyused as a counter for protecting or limiting concurrent access to agiven resource, such as to permitting at most "x" number of threads touse resource "y", for example.  Semaphore's are also convenient to useas synchronization objects to rondevous and signal activity and/orpost pending service requests between one thread thread and another.@tindex EventIn addition to Semaphore objects, GNU Common C++ supports "Event"objects.  Event objects are triggered "events" which are used tonotify one thread of some event it is waiting for from another thread.These event objects use a trigger/reset mechanism and are related tolow level conditional variables.@tindex ThreadKey@tindex AtomicCounter@cindex reference countingA special class, the ThreadKey, is used to hold state information thatmust be unique for each thread of context.  Finally, GNU Common C++supports a thread-safe "AtomicCounter" class.  This can often be usedfor reference counting without having to protect the counter with aseparate Mutex counter.  This lends to lighter-weight code.@c -----------------------------------------------------------------------@node Sockets@section Sockets@cindex Sockets@cindex Java socketsGNU Common C++ provides a set of classes that wrap and define theoperation of network "sockets".  Much like with Java, there are also arelated set of classes that are used to define and manipulate objectswhich act as "hostname" and "network addresses" for socketconnections.@tindex InetAddress@tindex InetHostAddress@tindex InetMaskAddress@tindex BroadcastAddressThe network name and address objects are all derived from a commonInetAddress base class. Specific classes, such as InetHostAddress,InetMaskAddress, etc, are defined from InetAddress entirely so thatthe manner a network address is being used can easily be documentedand understood from the code and to avoid common errors and accidentalmisuse of the wrong address object.  For example, a "connection" tosomething that is declared as a "InetHostAddress" can be kepttype-safe from a "connection" accidently being made to something thatwas declared a "BroadcastAddress".@tindex Socket@cindex QoS@cindex sockopt@cindex Dont-Route@cindex Keep-AliveThe socket is itself defined in a single base class named, quiteunremarkably, "Socket".  This base class is not directly used, but isprovided to offer properties common to other GNU Common C++ socketclasses, including the socket exception model and the ability to setsocket properties such as QoS, "sockopts" properties like Dont-Routeand Keep-Alive, etc.@tindex TCPStream@findex TCPStream::operator<<@findex TCPStream::operator>>The first usable socket class is the TCPStream.  Since a TCPconnection is always a "streamed" virtual circuit with flow control,the standard stream operators ("<<" and ">>") may be used withTCPStream directly.  TCPStream itself can be formed either byconnecting to a bound network address of a TCP server, or can becreated when "accepting" a network connection from a TCP server.@cindex TCPSocketAn implicit and unique TCPSocket object exists in GNU Common C++ torepresent a bound TCP socket acting as a "server" for receivingconnection requests.  This class is not part of TCPStream because suchobjects normally perform no physical I/O (read or write operations)other than to specify a listen backlog queue and perform "accept"operations for pending connections.  The GNU Common C++ TCPSocketoffers a Peek method to examine where the next pending connection iscoming from, and a Reject method to flush the next request from thequeue without having to create a session.@findex TCPSocket::onAcceptThe TCPSocket also supports a "onAccept" method which can be calledwhen a TCPStream related object is created from a TCPSocket.  Bycreating a TCPStream from a TCPSocket, an accept operationautomatically occurs, and the TCPSocket can then still reject theclient connection through the return status of it's OnAccept method.@tindex UDPSocketIn addition to connected TCP sessions, GNU Common C++ supports UDPsockets and these also cover a range of functionality.  Like aTCPSocket, A UDPSocket can be created bound to a specific networkinterface and/or port address, although this is not required.  UDPsockets also are usually either connected or otherwise "associated"with a specific "peer" UDP socket.  Since UDP sockets operate throughdiscreet packets, there are no streaming operators used with UDPsockets.@tindex UDPBroadcastIn addition to the UDP "socket" class, there is a "UDPBroadcast"class.  The UDPBroadcast is a socket that is set to send messages to asubnet as a whole rather than to an individual peer socket that it maybe associated with.@tindex UDPDuplexUDP sockets are often used for building "realtime" media streamingprotocols and full duplex messaging services.  When used in thismanner, typically a pair of UDP sockets are used together; one socketis used to send and the other to receive data with an associated pairof UDP sockets on a "peer" host.  This concept is represented throughthe GNU Common C++ UDPDuplex object, which is a pair of sockets thatcommunicate with another UDPDuplex pair.@tindex SocketPort@tindex SocketServiceFinally, a special set of classes, "SocketPort" and "SocketService",exist for building realtime streaming media servers on top of UDP andTCP protocols.  The "SocketPort" is used to hold a connected orassociated TCP or UDP socket which is being "streamed" and whichoffers callback methods that are invoked from a "SocketService"thread.  SocketService's can be pooled into logical thread pools thatcan service a group of SocketPorts.  A millisecond accurate "timer" isassociated with each SocketPort and can be used to time synchronizeSocketPort I/O operations.@c -----------------------------------------------------------------------@node Serial I/O@section Serial I/O@cindex Serial I/OGNU Common C++ serial I/O classes are used to manage serial devicesand implement serial device protocols.  From the point of view of GNUCommon C++, serial devices are supported by the underlying Posixspecified "termios" call interface.The serial I/O base class is used to hold a descriptor to a serialdevice and to provide an exception handling interface for all serialI/O classes.  The base class is also used to specify serial I/Oproperties such as communication speed, flow control, data size, andparity.  The "Serial" base class is not itself directly used inapplication development, however.GNU Common C++ Serial I/O is itself divided into two conceptual modes;frame oriented and line oriented I/O.  Both frame and line orientedI/O makes use of the ability of the underlying tty driver to bufferdata and return "ready" status from when select either a specifiednumber of bytes or newline record has been reached by manipulatingtermios c_cc fields appropriately.  This provides some advantage inthat a given thread servicing a serial port can block and wait ratherthan have to continually poll or read each and every byte as soon asit appears at the serial port.@tindex TTYStream@findex TTYStream::operator<<@findex TTYStream::operator>>@tindex ttystreamThe first application relevant serial I/O class is the TTYStreamclass.  TTYStream offers a linearly buffered "streaming" I/O sessionwith the serial device.  Furthermore, traditional C++ "stream"operators (<< and >>) may be used with the serial device.  A more"true" to ANSI C++ library format "ttystream" is also available, andthis supports an "open" method in which one can pass initial serialdevice parameters immediately following the device name in a singlestring, as in "/dev/tty3a:9600,7,e,1", as an example.@tindex TTYSessionThe TTYSession aggragates a TTYStream and a GNU Common C++ Threadwhich is assumed to be the execution context that will be used toperform actual I/O operations.  This class is very anagolous toTCPSession.@tindex TTYPort@tindex TTYServiceThe TTYPort and TTYService classes are used to form thread-poolserviced serial I/O protocol sets.  These can be used when one has alarge number of serial devices to manage, and a single (or limitednumber of) thread(s) can then be used to service the tty port objectspresent.  Each tty port supports a timer control and several virtualmethods that the service thread can call when events occur.  Thismodel provides for "callback" event management, whereby the servicethread performs a "callback" into the port object when events occur.Specific events supported include the expiration of a TTYPort timer,pending input data waiting to be read, and "sighup" connection breaks.@c -----------------------------------------------------------------------@node Block I/O@section Block I/O@cindex Block I/O@tindex RandomFileGNU Common C++ block I/O classes are meant to provide more convenientfile control for paged or random access files portably, and to answermany issues that ANSI C++ leaves untouched in this area.  A commonbase class, RandomFile, is provided for setting descriptor attributesand handling exceptions.  From this, three kinds of random file accessare supported.@tindex ThreadFile@findex pwread@findex pwwriteThreadFile is meant for use by a threaded database server wheremultiple threads may each perform semi-independent operations on agiven database table stored on disk.  A special "fcb" structure isused to hold file "state", and pread/pwrite is used whenever possiblefor optimized I/O.  On systems that do not offer pwread/pwrite, aMutex lock is used to protect concurrent lseek and read/writeoperations.  ThreadFile managed databases are assumed to be used onlyby the local server and through a single file descriptor.@tindex SharedFileSharedFile is used when a database may be shared between multipleprocesses.  SharedFile automatically applies low level byte-range"file locks", and provides an interface to fetch and releasebyte-range locked portions of a file.@tindex MappedFile@findex MappedFile::syncThe MappedFile class provides a portable interface to memory mappedfile access.  One can map and unmap portions of a file on demand, andupdate changed memory pages mapped from files immediately throughsync().@c -----------------------------------------------------------------------

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -