Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Programming
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Databases
Mail Systems
openSolaris
Eclipse Documentation
Techotopia.com
Virtuatopia.com

How To Guides
Virtualization
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Windows
Problem Solutions
Privacy Policy

  




 

 

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

Index


<

<cctype> 252

<cstdlib> 215

<ctime> 212

<exception> 38

<fstream> 169

<functional> 338

<iomanip> 196

<iosfwd> 163

<limits> 181, 203, 285

<memory> 35

<sstream> 179

<stdexcept> 38

<typeinfo> 557

A

abort( ) 27

Abstract Factory design pattern 651

abstraction, in program design 614

accumulate algorithm 413

activation record instance 58

adaptable function object 341

Adapter design pattern 636

adaptor: container 433, 487; function object 338; function pointer 351; iterator 487

adjacent_difference algorithm 415

adjacent_find algorithm 378

aggregation, design patterns 616

Alexandrescu, Andrei 294, 305

algorithm: accumulate 413; adjacent_difference 415; adjacent_find 378; applicators 405; binary_search 395; complexity 333; copy 326, 365; copy_backward 372; count 370; count_if 334, 371; counting 370; creating your own 419; equal 327, 385; equal_range 396; fill 369; fill_n 369; filling and generating 368; find 334, 377; find_end 379; find_first_of 378; find_if 378; for_each 355, 405; general utilities 417; generate 369; generate_n 369; generic 325; heap operations 403; includes 400; inner_product 414; inplace_merge 399; iter_swap 419, 457; lexicographical_compare 385; lower_bound 395; make_heap 404; manipulating sequences 372; max 419; max_element 380; merge 399; merging 398; min 418; min_element 379; mismatch 386; next_permutation 373; nth_element 394; numeric 413; ordering 393; partial_sort 394; partial_sort_copy 394; partial_sum 414; partition 374; pop_heap 404; predicate 329; prev_permutation 373; push_heap 404; random_shuffle 374; range of sequence in 326; remove 389; remove_copy 389; remove_copy_if 329, 339, 350, 390; remove_if 389; removing elements 389; replace 380; replace_copy 380; replace_copy_if 330, 380; replace_if 330, 380; reverse 372; reverse_copy 372; rotate 373; rotate_copy 373; search 379; search_n 379; searching and replacing 377; set operations 400; set_difference 401; set_intersection 401; set_symmetric_difference 402; set_union 401; sort 366, 393; sort_heap 404; sorting 393; stable_partition 374; stable_sort 366, 393; swap 419; swap_ranges 373; transform 347, 349, 355, 405; unique 390; unique_copy 390; upper_bound 395; utilities 417

ANSI/ISO C++ Committee 9

applicator algorithms 405

applicator, iostreams manipulator 200

applying a function to a container 255

argument_type 342

argument-dependent lookup 274, 278; disabling 275

assert macro 66

assertion 66; side effects in an 67

Assignable 337

associative container 433, 513

atof( ) 181

atoi( ) 181

atomic operation 732

auto_ptr 35; not for containers 437

automated testing 71

automatic type conversion, and exception handling 23

B

back_insert_iterator 448, 482

back_inserter( ) 328, 370, 372, 418, 448

bad_cast exception class 40, 557

bad_exception class 44

bad_typeid exception class 40, 559

badbit 165

basic_istream 158, 216

basic_ostream 158, 217

basic_string 134, 217, 241

Becker, Pete 11

before( ), RTTI function 559

behavioral design patterns 616

bidirectional iterator 446

BidirectionalIterator 364

binary files 172, 214

binary function 337

binary predicate 337

binary search 63

binary_function 342, 353; first_argument_type 342; result_type 342; second_argument_type 342

binary_negate function object 341

binary_search algorithm 395

bind1st function object adaptor 339

bind2nd function object adaptor 338, 350, 371

binder1st function object 339

binder2nd function object 339

bitset 229, 506, 540; to_string( ) 241

blocking, and threads 734

book errors, reporting 10

Bright, Walter 8, 11

broadcast( ), threading 734, 742, 757

buffering, stream 173

Builder design pattern 660

busy wait, threading 732, 743

C

cancel( ), ZThread library function 717

Cancelable, ZThread library class 717

cast: downcast 551; dynamic_cast 555; runtime 551; runtime type identification, casting to intermediate levels 560

catch 20; catching any exception 25

cerr 158

cfront 574

Chain of Responsibility design pattern 642

chaining, in iostreams 159

change, vector of change 614

char_traits 217, 241, 287

character traits 217; compare( ) 217

cin 158

class: hierarchies and exception handling 24; invariant 69; maintaining library source 204; wrapping 151

class template: partial ordering 263; partial specialization 263

cleaning up the stack during exception handling 28

clear( ) 166, 175

close( ) 168

code bloat, of templates 268

code invariant 63

cohesion 49

Collecting Parameter design pattern (idiom) 618

command line, interface 162

Command pattern 626; decoupling 628

Committee, ANSI/ISO C++ 9

compilation, of templates 315

compile time: assertions 304; error checking 155; looping 299; selection 303

complexity of algorithms 333

compose non-standard function object adaptor 360

composition, and design patterns 614, 615

concurrency 691; blocking 734; Command pattern 628; when to use it 771

ConcurrentExecutor (Concurrency) 704

Condition class, threading 742

console I/O 162

constructor: default constructor synthesized by the compiler 620; design patterns 616; exception handling 29, 30, 57; failing 57; order of constructor and destructor calls 562; private constructor 620; protected 581; simulating virtual constructors 654; virtual functions inside constructors 654

container 429; adaptor 433, 487; associative 433, 513; bitset 506, 540; cleaning up 437, 534; combining STL containers 530; creating custom 536; deque 434, 465; duplicate keys 523; extended STL containers 440; list 434, 471; map 513, 521; multimap 513, 523; multiple membership problem 438; multiset 513, 527; of pointers 436; priority_queue 496; queue 491; reversible 445; sequence 433; sequence operations 454; set 479, 513; stack 487; valarray 540; value-based 434; vector 434, 457; vector<bool> 506, 511

contract, design by 68

conversion, automatic type conversions and exception handling 23

cooperation between threads 741

Coplien, James 296, 655

copy algorithm 326, 365

copy_backward algorithm 372

copy-on-write 634

count algorithm 370

count_if algorithm 334, 371

CountedPtr, reference-counting template in ZThread library (Concurrency) 714

counting algorithms 370

cout 158

covariance, of exception specifications 47

Crahen, Eric 11, 694

creational design patterns 615

critical section, in thread programming 719

curiously recurring template pattern 294, 624

Cygwin, and ZThreads 696

Czarnecki, Krysztof 300

D

datalogger 211

dead thread 734

deadlock 720, 764; conditions for 769

debugging 87

dec 187

declaration, forward 163

default constructor: synthesized by the compiler 620

dependent base class 278

dependent name 274

deque 434, 465

design: abstraction in program design 614; cohesion 49; decisions 66; exception-neutral 52; exception-safe 48

design by contract 68

design patterns 613; Abstract Factory 651; Adapter 636; aggregation 616; behavioral 616; Builder 660; Chain of Responsibility 642; Collecting Parameter idiom 618; Command 626; constructors 616; creational 615; destructors 616; Double Dispatching 679; Factory Method 581, 645; Messenger idiom 617; Multiple Dispatching 679; Observer 667; Proxy 632; simulating virtual constructors 654; Singleton 460, 619; State 634; Strategy 640; structural 615; Template Method 639; vector of change 614; Visitor 683

destructor 659; design patterns 616; exception handling 28, 57; explicit call 453; order of constructor and destructor calls 562; virtual 581

diamond inheritance 588

difference_type 370

dining philosophers, threading 764

dispatching: Double Dispatching design pattern 679; Multiple Dispatching design pattern 679

distance( ) 417

divides function object 341

documentation, library 101

document-view architecture 667

domain_error exception class 40

dominance 601

Double Dispatching design pattern 653, 679

downcast 551

dynamic type, of an object 557

dynamic_cast 555; casting to intermediate levels 560; difference between dynamic_cast and typeid, runtime type identification 561; for polymorphic types 556

E

effectors 201

efficiency: runtime type identification 565; threads and 693

Eisenecker, Ulrich 300

ellipses, with exception handling 25

endl 195

envelope, and letter classes 655

eofbit 166

epsilon( ) 181

equal algorithm 327, 385

equal_range algorithm 396

equal_to function object 339, 341

EqualityComparable 337

errno 16

error: handling 15; handling, in C 16; recovery 15; reporting errors in book 10

event-driven programming, and the Command pattern 628

exception class 38; what( ) 38

exception handling 15; asynchronous events 53; atomic allocations for safety 32; automatic type conversions 23; bad_cast exception class 40, 557; bad_exception class 44; bad_typeid exception class 40, 559; catching an exception 20; catching any exception 25, 26; catching by reference 23; catching via accessible base 25; class hierarchies 24; cleaning up the stack during a throw 28; constructors 29, 30, 57; destructors 28, 36, 57; domain_error exception class 40; ellipses 25; exception class 38; exception class, what( ) 38; exception handler 20; exception hierarchies 56; exception matching 23; exception neutral 52; exception safety 48; exception specifications 40; exception type 39; incomplete objects 29; inheritance 24; invalid_argument exception class 40; length_error exception class 40; logic_error class 38; memory leaks 29; multiple inheritance 56; naked pointers 30; object slicing and 23; out_of_range exception class 40; overhead of 58; programming guidelines 52; references 34, 56; resource management 30; rethrowing an exception 26, 52; runtime_error class 38; set_terminate( ) 27; set_unexpected( ) 41; specifications, and inheritance 46; specifications, covariance of 47; specifications, when not to use 47; stack unwinding 19; Standard C++ library exceptions 38; terminate( ) 44; termination vs. resumption 22; testing 79; throwing & catching pointers 57; throwing an exception 18, 19; typical uses of exceptions 54; uncaught exceptions 26, 28; unexpected( ) 41; when to avoid 52; zero-cost model 60; ZThreads (Concurrency) 708

exception specifications 40; covariance of 47; inheritance 46; when not to use 47

exclusion, mutual, in threads 719

Executors, ZThread (Concurrency) 702

explicit instantiation, of templates 316

export keyword 319

exported templates 319

expression templates 308

extractor, stream 158

Extreme Programming (XP) 71, 615

F

facet: locale 220

Factory Method design pattern 581, 645

fail( ) 175

failbit 160, 166

Fibonacci 298, 636

file streams, close( ) 168

file, iostreams 156, 162

FILE, stdio 152

fill algorithm 369

fill_n algorithm 369

filling and generating algorithms 368

find algorithm 334, 377

find_end algorithm 379

find_first_of algorithm 378

find_if algorithm 378

first_argument_type 342

flock( ), and SynchronousExecutor (Concurrency) 705

flush, iostreams 195

for_each algorithm 355, 405

format fields 188

format flags: dec 187; hex 187; ios; showbase 187; showpoint 187; showpos 187; skipws 187; unitbuf 187; uppercase 187; oct 187

formatted I/O 186

formatting: in-core 179; manipulators, iostreams 194; output stream 186

forward declaration 163

forward iterator 446

forward_iterator_tag 447

ForwardIterator 363

framework, unit test 75

friend template 284

friends, of templates 279

front_insert_iterator 448

front_inserter( ) 418, 448

fseek( ) 176

fstream 168; simultaneous input and output 172

function: applying a function to a container 255; binary 337; unary 337

function object 335, 626; adaptable 341; adaptor 338; binary_negate 341; bind1st adaptor 339; bind2nd adaptor 338, 350; binder1st 339; binder2nd 339; classification 336; divides 341; equal_to 339, 341; greater 338, 341, 371; greater_equal 341; less 341; less_equal 341; logical_and 341; logical_not 341; logical_or 341; minus 340; modulus 341; multiplies 341; negate 341; not_equal_to 341; not1 adaptor 339; plus 340; unary_negate 341

function object adaptor 338; bind2nd 371; not1 352; pointer_to_binary_function 353; pointer_to_unary_function 352

function pointer adaptor 351; ptr_fun 351

function template 245; address of 251; explicit qualification 246; overloading 249; partial ordering of 259; specialization 261; type deduction parameters in 245

function-call operator 335

function-level try blocks 36

functor 626; see function object 335

G

Gang of Four (GoF) 613

general utility algorithms 417

generate algorithm 369

generate_n algorithm 369

generator 337, 369

generic algorithms 325

get pointer 177

get( ) 170; overloaded versions 165

getline( ) 164, 171

getline( ), for strings 129

getPriority( ) 711

GoF, Gang of Four 613

goodbit 166

greater function object 338, 341, 371

greater_equal function object 341

Guard template, ZThread (concurrency) 721

H

handler, exception 20

handshaking, between concurrent tasks 742

hash_map non-standard container 539

hash_multimap non-standard container 539

hash_multiset non-standard container 539

hash_set non-standard container 539

heap operations 403

hex 187

hierarchy, object-based 573

I

I/O: console 162; interactive 162; raw 165; threads, blocking 737

i18n, see internationalization 216

ifstream 156, 168, 174

ignore( ) 170

imbue( ) 220

implementation inheritance 579

includes algorithm 400

inclusion model, of template compilation 315

incomplete type 163

in-core formatting 179

inheritance: design patterns 614; diamond 588; hierarchies 573; implementation 579; interface 575

inheritance, multiple 573, 673; avoiding 603; dominance 601; name lookup 599; runtime type identification 560, 563, 570

initialization: controlling initialization order 621; lazy 620; object 596; Resource Acquisition Is Initialization (RAII) 32, 36, 582; zero initialization 522

inner class idiom, adapted from Java 671

inner_product algorithm 414

inplace_merge algorithm 399

input iterator 446

input_iterator_tag 447

InputIterator 363

insert( ) 448

insert_iterator 372, 448, 482

inserter( ) 372, 418, 448

inserter, stream 158

instantiation, template 260

interactive I/O 162

interface: class 576; command-line 162; extending an 603; inheritance 575; repairing an interface with multiple inheritance 603; responsive user 700

internationalization 216

interrupt( ), threading 735

interrupted status, threading 739

Interrupted_Exception, threading 739

invalid_argument exception class 40

invalidation, iterator 463

invariant: class 69; code 63; loop 64

ios: app 172; ate 172; basefield 188; beg 176; binary 172, 214; cur 176; end 176; failbit 160; fill( ) 190; in 171; out 172; precision( ) 190; showbase 187; showpoint 187; showpos 187; skipws 187; trunc 172; unitbuf 187; uppercase 187; width( ) 190

ios_base 157

iostate 168

iostreams 156; applicator 200; automatic 189; badbit 165; binary mode 172, 214; buffering 173; clear function 166, 175; dec manipulator 195; endl manipulator 195; eofbit 166; errors 165; exceptions 167; exceptions function 167; extractor 158; fail function 175; failbit 166; failure exception type 167; files 162; fill( ) 190; fixed 196; flags( ) 186; flush 195; fmtflags type 186; format fields 188; format flags 186; formatting 186; fseek( ) 176; get( ) 170; getline( ) 171; goodbit 166; hex manipulator 195; ignore( ) 170; imbue( ) 220; inserter 158; internal 196; ios::basefield 188; ios::dec 189; ios::fixed 189; ios::hex 189; ios::internal 190; ios::left 190; ios::oct 189; ios::right 190; ios::scientific 189; iostate type 168; left 196; locales 216; manipulators 194; manipulators, creating 199; narrow 216; narrow function 218; noshowbase 195; noshowpoint 196; noshowpos 195; noskipws 196; nouppercase 195; oct manipulator 195; open modes 171; operator << 158; operator >> 158; positioning 175; precision( ) 190, 213; resetiosflags manipulator 196; right 196; scientific 196; seeking in 175; setbase manipulator 197; setf( ) 187, 188, 213; setfill manipulator 197; setiosflags manipulator 196; setprecision manipulator 197; setstate function 166; setw manipulator 197, 213; showbase 195; showpoint 196; showpos 195; skipws 196; smanip type 201; string I/O with 179; text mode 172; threads, colliding output 727; unsetf( ) 188; uppercase 195; wide 216; widen function 218; width( ) 190; write( ) 213; ws manipulator 195

istream 156; get( ) 164; getline( ) 164; read( ) 165; seekg( ) 176; tellg( ) 176

istream_iterator 333, 446, 450

istreambuf_iterator 446, 451, 481

istringstream 156, 179

iter_swap algorithm 419, 457

iterator 429, 615; adapting a class to produce 637; adaptor 487; bidirectional 446; categories 446; forward 446; input 446; invalidation 463; istream 333; ostream 332; output 446; past-the-end 443; random-access 446; reverse 445; stream 331; stream iterator 450; tag 447; traits 366

iterator_traits 366

J

Josuttis, Nico 101

K

King, Jamie 10

Koenig, Andrew 274

Kreft, Klaus 314, 780

L

Lajoie, Josee 60

Langer, Angelika 314, 780

lazy initialization 620, 634

length_error exception class 40

less function object 341

less_equal function object 341

LessThanComparable 337

letter, envelope and letter classes 655

lexicographical_compare algorithm 385

library: documentation 101; maintaining class source 204

line input 162

linear search 377

Linux, and ZThreads 696

list 434, 471; merge( ) 474; remove( ) 474; reverse( ) 472; sort( ) 472; unique( ) 474; vs. set 476

locale 216, 218; collate category 219; ctype category 219; facet 220; iostreams 216; messages category 219; monetary category 219; money_get facet 220; money_punct facet 220; money_put facet 220; numeric category 219; time category 219; time_get facet 220; time_put facet 220

localtime( ) 213

logic_error class 38

logical_and function object 341

logical_not function object 341

logical_or function object 341

longjmp( ) 16

loop: invariant 64; unrolling 301

lower_bound algorithm 395

M

machine epsilon 181

maintaining class library source 204

make_heap algorithm 404, 499

make_pair( ) 417

manipulating sequences 372

manipulators 160; creating 199; iostreams formatting 194; with arguments 196

map 521; keys and values 521

max algorithm 419

max_element algorithm 380

mem_fun member pointer adaptor 355

mem_fun_ref member pointer adaptor 355

member templates 242; vs. virtual 245

memory leaks 90

memory management, and threads 711

merge algorithm 399

merging algorithms 398

Messenger design pattern (idiom) 617

metaprogramming 297; compile-time assertions 304; compile-time looping 299; compile-time selection 303; loop unrolling 301; Turing completeness of 298

Meyer, Bertrand 68

Meyers, Scott 60, 623

min algorithm 418

min_element algorithm 379

minus function object 340

mismatch algorithm 386

mixin: class 579; parameterized 583

model-view-controller (MVC) 667

modulus function object 341

money_get 220

money_punct 220

money_put 220

multimap 523

Multiple Dispatching design pattern 679

multiple inheritance 573, 673; avoiding 603; dominance 601; duplicate subobjects 585; exception handling 56; name lookup 599; repairing an interface 603; runtime type identification 560, 563, 570

multiplies function object 341

multiprocessor machine, and threading 692

multiset 527; equal_range( ) 529

multitasking 691

multithreading 691; drawbacks 771; ZThread library for C++ 694

mutex: simplifying with the Guard template 721; threading 742; ZThread FastMutex 731

mutual exclusion, in threads 719

Myers, Nathan 11, 251, 285, 452, 481, 482

N

naked pointers, and exception handling 30

name lookup, and multiple inheritance 599

name( ), RTTI function 559

narrow streams 216

narrow( ) 218

negate function object 341

new, placement 91

newline, differences between DOS and Unix 172

next_permutation algorithm 373

not_equal_to function object 341

not1 function object adaptor 339, 352

nth_element algorithm 394

numeric algorithms 413

numeric_limits 203, 285

O

object: initialization 596; object-based hierarchy 573; slicing, and exception handling 23

Observable 668

Observer design pattern 667

oct 187

ofstream 156, 168

one-definition rule 622

open modes, iostreams 171

operator new( ) 90

operator void*( ), for streams 167

operator( ) 229, 335, 339

operator++( ) 234

optimization, throughput, with threading 692

order: controlling initialization 621; of constructor and destructor calls 562

ordering: algorithms 393; strict weak 337

ostream 156; fill( ) 160; manipulators 160; seekp( ) 176; setfill( ) 160; setw( ) 160; tellp 176; write( ) 165

ostream_iterator 332, 365, 446, 451

ostreambuf_iterator 446, 451

ostringstream 156, 179; str( ) 182

out_of_range exception class 40

output: iterator 446; stream formatting 186

output_iterator_tag 447

OutputIterator 363

overhead, exception handling 58

overloading, function template 249

P

parameter, template 227

parameterized mixin 583

Park, Nick 257

partial ordering: class templates 263; function templates 259

partial specialization, template 263

partial_sort algorithm 394

partial_sort_copy algorithm 394

partial_sum algorithm 414

partition algorithm 374

past-the-end iterator 443

patterns, design patterns 613

perror( ) 16

philosophers, dining, and threading 764

placement new 91

Plauger, P. J. 101

plus function object 340

pointer to member adaptor: mem_fun 355; mem_fun_ref 355

pointer, smart 437

pointer_to_binary_function function object adaptor 353

pointer_to_unary_function function object adaptor 352

policies 291

policy class 293

polymorphism 564

PoolExecutor (Concurrency) 703

pop_heap algorithm 404, 499

POSIX standard 145

postcondition 68

precision( ) 213

precondition 68

predicate 329; binary 337; unary 337

prev_permutation algorithm 373

printf( ) 154; error code 15

priority, thread 709

priority_queue 496; as a heap 499; pop( ) 500

private constructor 620

process, threading and 691

producer-consumer, threading 747

programming paradigms 573

protected constructor 581

Proxy design pattern 632

ptr_fun function pointer adaptor 351

pure virtual function 576

push_back( ) 434, 448, 482

push_front( ) 434, 448

push_heap algorithm 404, 499

put pointer 176

Q

qualified name 274, 278

queue 491

queues, thread, for problem-solving 750

quicksort 366

R

race condition 717

RAII 32, 36, 582

raise( ) 16

rand( ) 215

RAND_MAX 215

random_shuffle algorithm 374

random-access iterator 446

RandomAccessIterator 364

range, of sequence 326

raw byte I/O 165

raw_storage_iterator 446, 452

rbegin( ) 445, 448

rdbuf( ) 174

read( ) 165

refactoring 70

reference counting 582, 634; ZThreads (Concurrency) 712

references: bad_cast 557; exception handling 34, 56

remove algorithm 389

remove_copy algorithm 389

remove_copy_if algorithm 329, 339, 350, 390

remove_if algorithm 389

removing elements, algorithm 389

rend( ) 445, 448

reordering, stable and unstable 366

replace algorithm 380

replace_copy algorithm 380

replace_copy_if algorithm 330, 380

replace_if algorithm 330, 380

reporting errors in book 10

requirements 70

reserve( ) 458

resize( ) 456

Resource Acquisition Is Initialization (RAII) 32, 36, 582

responsive user interfaces 700

result_type 342

resumption, vs. termination, exception handling 22

rethrow, exception 26, 52

reverse algorithm 372

reverse_copy algorithm 372

reverse_iterator 445, 448, 487

reversible container 445

rope non-standard string class 539

rotate algorithm 373

rotate_copy algorithm 373

Runnable 696

runtime cast 551

runtime stack 228

runtime type identification 551; casting to intermediate levels 560; const and volatile and 558; difference between dynamic_cast and typeid 561; efficiency 565; mechanism & overhead 570; misuse 564; multiple inheritance 560, 563, 570; templates and 562; type_info 570; type_info class 557; type_info::before( ) 559; type_info::name( ) 559; typeid operator 557; void pointers 561; VTABLE 570; when to use it 564

runtime_error class 38

S

Saks, Dan 282

Schwarz, Jerry 201

search algorithm 379

search_n algorithm 379

searching and replacing algorithms 377

second_argument_type 342

seekg( ) 176

seeking in iostreams 175

seekp( ) 176

separation model, of template compilation 319

sequence: at( ) 470; container 433; converting between sequences 467; deque 465; erase( ) 457; expanding with resize( ) 456; insert( ) 457; list 471; operations 454; operator[ ] 471; random-access 470; swap( ) 457; swapping sequences 477; vector 457

serialization: object 215; thread 750

set 479, 513; find( ) 480; operations 400; ordering of 480; STL set class example 432; vs. list 476

set_difference algorithm 401

set_intersection algorithm 401

set_symmetric_difference algorithm 402

set_terminate( ) 27

set_unexpected( ) 41

set_union algorithm 401

setf( ) 187, 213

setjmp( ) 16

setPriority( ) 711

setw( ) 213

Sieve of Eratosthenes 119

signal( ) 16, 53; threading 734, 742

Singleton 460, 619; implemented with curiously recurring template pattern 624; Meyers Singleton 623; ZThreads library (concurrency) 728

sleep( ), threading 707, 734

slice, valarray 542

slicing, object slicing and exception handling 23

slist non-standard container 539

Smalltalk 573

smanip 201

smart pointer 437

software quality 63

sort algorithm 366, 393

sort_heap algorithm 404

sorting algorithms 393

specialization: function template 261; template 260

specification, exception 40

srand( ) 214

stable reordering 366

stable_partition algorithm 374

stable_sort algorithm 366, 393

stack 487; exception safety of 489; pop( ) 489; push( ) 489; top( ) 489

stack frame 58

stack unwinding 19

Standard C 9

Standard C++ 9; concurrency 694; exception types 38

State design pattern 634

stdio 151

STL extensions 538

Strategy design pattern 640

strcmp( ) 217

stream 156; errors 165; iterator 331, 450; output formatting 186; state 165

streambuf 173; get( ) 174; rdbuf( ) 174

streampos 176

strict weak ordering 337

StrictWeakOrdering 374, 403

string 103; append( ) 110; at( ) 132; c_str( ) 131; capacity( ) 111; case-insensitive search 120; character traits 134; compare( ) 131; concatenation 117; empty( ) 356; erase( ) 126; find( ) 115; find_first_not_of( ) 118; find_first_of( ) 118; find_last_not_of( ) 118; find_last_of( ) 118; getline( ) 129; indexing operations 133; insert( ) 110; iterator 108; length( ) 111; memory management 110, 114; npos member 114; operator!= 129; operator[ ] 132; operator+ 117; operator+= 117; operator< 129; operator<= 129; operator== 129; operator> 129; operator>= 129; reference-counted 104; relational operators 129; replace( ) 112; reserve( ) 111; resize( ) 111; rfind( ) 118; size( ) 111; stream I/O 156; substr( ) 107; swap( ) 132; transforming strings to typed values 181

string streams 179

stringbuf 183

stringizing, preprocessor operator 193

Stroustrup, Bjarne 101

struct tm 213

structural design patterns 615

subobject, duplicate subobjects in multiple inheritance 585

subtasks 691

suite, test 79

surrogate, in design patterns 631

swap algorithm 419

swap_ranges algorithm 373

synchronization: (concurrency) example of problem from lack of synchronization 732; blocking 734; thread 719

Synchronization_Exception, ZThread library 698, 703

synchronized, threading, wrapper for an entire class 723

SynchronousExecutor (Concurrency) 705

T

tag, iterator tag classes 447

task, defining for threading 696

tellg( ) 176

tellp( ) 176

template: argument-dependent lookup in 274; code bloat, preventing 268; compilation 274; compilation models 315; compilation, two-phase 274; curiously recurring template pattern 294; default arguments 230; dependent names in 274; explicit instantiation 316; export 319; expression templates 308; friend template 284; friends 279; function 245; idioms 285; inclusion compilation model 315; instantiation 260; keyword 240; member 242; member, and virtual keyword 245; metaprogramming 297; name lookup issues 273; names in 273; non-type parameters 228; parameters 227; partial ordering of class templates 263; partial ordering of function templates 259; partial specialization 263; policy-based design 291; qualified names in 274, 278; runtime type identification and 562; separation compilation model 319; specialization 260; template template parameters 232; traits 285

Template Method design pattern 639

terminate( ) 27, 44; uncaught exceptions 26

terminating threads 735

termination problem, concurrency 727

termination, vs. resumption, exception handling 22

test: automated unit testing 71; Boolean expressions in testing 72; framework 75; suite 79; test-first programming 71; unit 70

Test class 76

TestSuite framework 75

text processing 103

thread 691; atomic operation 732; blocked 734; broadcast( ) 734, 742, 757; busy wait 732, 743; Cancelable, ZThread library class 717; colliding over resources, improperly accessing shared resources 715; concurrency 691; Condition class for wait( ) and signal( ) 742; cooperation 741; dead state 734; deadlock 720, 764; deadlock, and priorities 709; dining philosophers 764; drawbacks 771; example of problem from lack of synchronization 732; getPriority( ) 711; handshaking between tasks 742; I/O and threads, blocking 737; interrupt( ) 735; interrupted status 739; Interrupted_Exception 739; iostreams and colliding output 727; memory management 711; multiple, for problem-solving 741; mutex, for handshaking 742; mutex, simplifying with the Guard template 721; new state 734; order of task shutdown 717; order of thread execution 708; priority 709; producer-consumer 747; queues solve problems 750; race condition 717; reference counting 712; reference counting with CountedPtr 714; runnable state 734; serialization 750; setPriority( ) 711; sharing resources 711; signal( ) 734, 742; sleep( ) 707, 734; states 734; synchronization 719; synchronization and blocking 734; synchronized wrapper for an entire class 723; termination 735; termination problem 727; thread local storage 724; threads and efficiency 693; TQueue, solving threading problems with 750; wait( ) 734, 742; when to use threads 771; yield( ) 706; ZThread FastMutex 731

ThreadedExecutor (Concurrency) 702

throughput, optimize 692

throw 19

throwing an exception 18

time( ) 214

time_get 220

time_put 220

tolower 252

toupper 252

TQueue, solving threading problems with 750

trace: file 88; macro 87

traits 285; iterator 366

transform algorithm 252, 347, 349, 355, 405

transforming character strings to typed values 181

try 20

try block 20; function-level 36

type: automatic type conversions and exception handling 23; deduction, of function template parameters 245; incomplete 163; runtime type identification (RTTI) 551

type_info: name function 244; structure 570

type_info class 557

type_info::before( ) 559

type_info::name( ) 559

typeid operator 244, 557; difference between dynamic_cast and typeid, runtime type identification 561

typename: keyword 237; typedef 240; versus class 240

typing, weak 579

U

unary function 337

unary predicate 337

unary_composer non-standard function object 360

unary_function 342, 352; argument_type 342; result_type 342

unary_negate function object 341

uncaught exceptions 26

uncaught_exception( ) 52

unexpected( ) 41

Unicode 216

unique algorithm 390

unique_copy algorithm 390

unit buffering 188

unit test 70

unstable reordering 366

upcast 603

upper_bound algorithm 395

Urlocker, Zack 608

user interface, responsive, with threading 692, 700

utility algorithms 417

V

valarray 540; slice 542

value_type 450

van Rossum, Guido 773

Vandevoorde, Daveed 308

vector 457; reserve( ) 458

vector of change 614

vector<bool> 263, 506, 511

Veldhuizen, Todd 308

virtual: base class 563, 589; base, initialization of 592; destructor 581; function table 654; pure virtual functions 576; simulating virtual constructors 654; virtual functions inside constructors 654

Visitor design pattern 683

void 561

VPTR 654

VTABLE 654; runtime type identification 570

W

wait( ), threading 734, 742

wchar_t 216

wcscmp( ) 217

weak typing 579

web servers, multiprocessor 692

wide: character 216; stream 216; stream function, wcscmp( ) 217

widen( ) 218

Will-Harris, Daniel 11

wrapping, class 151

write( ) 165, 213

ws 195

X

XP, Extreme Programming 71, 615

Y

yield( ), threading 706

Z

zero initialization 522

Zolman, Leor 320

ZThread: Cancelable class 717; Executors 702; installing the library 695; multithreading library for C++ 694





[1] You might be surprised when you run the example some C++ compilers have extended longjmp( ) to clean up objects on the stack. This behavior is not portable.

[2] The BASIC language has long supported a limited form of resumptive exception handling with its ON ERROR facility.

[3] You might always want to specify exception objects by const reference in exception handlers. (It s rare to modify and rethrow an exception.) However, we are not dogmatic about this practice.

[4] Only unambiguous, accessible base classes can catch derived exceptions. This rule minimizes the runtime overhead needed to validate exceptions. Remember that exceptions are checked at runtime, not at compile time, and therefore the extensive information available at compile time is not available during exception handling.

[5] Note that there s an exception class called std::out_of_range in the C++ Standard Library, intended to be used in situations such as this.

 

[6] For more detail on auto_ptr, see Herb Sutter s article entitled, Using auto_ptr Effectively in the October 1999 issue of the C/C++ Users Journal, pp. 63 67.

[7] If you re interested in a more in depth analysis of exception safety issues, the definitive reference is Herb Sutter s Exceptional C++, Addison Wesley, 2000.

[8] The library function uncaught_exception( ) returns true in the middle of stack unwinding, so technically you can test uncaught_exception( ) for false and let an exception escape from a destructor. We ve never seen a situation in which this constituted good design, however, so we only mention it in this footnote.

[9] Some compilers do throw exceptions in these cases, but they usually provide a compiler option to disable this (unusual) behavior.

[10] Check out the Boost smart pointer types at https://www.boost.org/libs/smart_ptr/index.htm. Some of these are being considered for inclusion in the next revision of Standard C++.

[11] This depends on how much return code checking you would have to insert if you weren t using exceptions.

[12] Borland enables exceptions by default; to disable exceptions use the
x compiler option. Microsoft disables support by default; to turn it on, use the GX option. With both compilers use the c option to compile only.

[13] The GNU C++ compiler uses the zero cost model by default. Metrowerks Code Warrior for C++ also has an option to use the zero cost model.

[14] Thanks to Scott Meyers and Josee Lajoie for their insights on the zero cost model. You can find more information on how exceptions work in Josee s excellent article, Exception Handling: Behind the Scenes, C++ Gems, SIGS, 1996.

[15] He invented Quicksort, among other things.

[16] As quoted in Programming Language Pragmatics, by Michael L. Scott, Morgan Kaufmann, 2000.

[17] See his book, Object Oriented Software Construction, Prentice Hall, 1994.

[18] This is still an assertion conceptually, but since we don t want to halt execution, the assert( ) macro is not appropriate. Java 1.4, for example, throws an exception when an assertion fails.

[19] There is a nice phrase to help remember this phenomenon: Require no more; promise no less, first coined in C++ FAQs, by Marshall Cline and Greg Lomow (Addison Wesley, 1994). Since pre conditions can weaken in derived classes, we say that they are contravariant, and, conversely, post conditions are covariant (which explains why we mentioned the covariance of exception specifications in Chapter 1).

[20] This section is based on Chuck s article, The Simplest Automated Unit Test Framework That Could Possibly Work, C/C++ Users Journal, Sept. 2000.

[21] A good book on this subject is Martin Fowler s Refactoring: Improving the Design of Existing Code (Addison Wesley, 2000). See also https://www.refactoring.com. Refactoring is a crucial practice of Extreme Programming (XP).

[22] See Extreme Programming Explained: Embrace Change by Kent Beck, Addison Wesley 1999. Lightweight methodologies such as XP have joined forces in the Agile Alliance (see https://www.agilealliance.org/home).

[23] Our Date class is also internationalized, in that it supports wide character sets. This is introduced at the end of the next chapter.

[24] See https://sourceforge.net/projects/cppunit for more information.

[25] This is a key principle of Extreme Programming.

[26] Runtime Type Identification, discussed in chapter 9. Specifically, we use the name( ) member function of the typeinfo class. If you re using Microsoft Visual C++, you need to specify the compile option /GR. If you don t, you ll get an access violation at runtime.

[27] In particular, we use stringizing (via the # preprocessing operator) and the predefined macros __FILE__ and __LINE__. See the code later in the chapter.

[28] Batch files and shell scripts work well for this. The Suite class is a C++ based way of organizing related tests.

[29] Our key technical reviewer, Pete Becker of Dinkumware. Ltd., brought to our attention that it is illegal to use macros to replace C++ keywords. His take on this technique was as follows: This is a dirty trick. Dirty tricks are sometimes necessary to figure out why code isn t working, so you may want to keep this in your toolbox, but don t ship any code with it. Caveat programmer.

[30] Thanks to Reg Charney of the C++ Standards Committee for suggesting this trick.

[31] Some of the material in this chapter was originally created by Nancy Nicolaisen.

[32] It s difficult to make reference counting implementations thread safe. (See Herb Sutter, More Exceptional C++, pp. 104 14). See Chapter 10 for more on programming with multiple threads.

[33] It is an abbreviation for no position, and is the largest value that can be represented by the string allocator s size_type (std::size_t by default).

[34] Discussed in depth in Chapter 6.

[35] To keep the exposition simple, this version does not handle nested tags, such as comments.

[36] It is tempting to use mathematics here to factor out some of these calls to erase( ), but since in some cases one of the operands is string::npos (the largest unsigned integer available), integer overflow occurs and wrecks the algorithm.

[37] For the safety reasons mentioned, the C++ Standards Committee is considering a proposal to redefine string::operator[] to behave identically to string::at( ) for C++0x.

[38] Your implementation can define all three template arguments here. Because the last two template parameters have default arguments, such a declaration is equivalent to what we show here.

[39] Beware that some versions of Microsoft Word erroneously replace single quote characters with an extended ASCII character when you save a document as text, which causes a compile error. We have no idea why this happens. Just replace the character manually with an apostrophe.

[40] POSIX, an IEEE standard, stands for Portable Operating System Interface and is a generalization of many of the low level system calls found in UNIX systems.

[41] Explained in depth in Chapter 5.

[42] For this reason, you can write ios::failbit instead of ios_base::failbit to save typing.

[43] It is customary to use operator void*( ) in preference to operator bool( ) because the implicit conversions from bool to int may cause surprises, should you incorrectly place a stream in a context where an integer conversion can be applied. The operator void*( ) function will only be called implicitly in the body of a Boolean expression.

[44] An integral type used to hold single bit flags.

[45] A more in depth treatment of stream buffers and streams in general can be found in Langer & Kreft s, Standard C++ iostreams and Locales, Addison Wesley, 1999.

[46] For more information on machine epsilon and floating point computation in general, see Chuck s article, The Standard C Library, Part 3, C/C++ Users Journal, March 1995, available at www.freshsources.com/1995006a.htm.

[47] Before putting nl into a header file, make it an inline function.

[48] Jerry Schwarz is the designer of iostreams.

[49] See the Langer & Kreft book mentioned earlier for more detailed information.

[50] See, for example, Dinkumware s Abridged library at https://www.dinkumware.com. This library omits locale support. and exception support is optional.

[51] Vandevoorde and Josuttis, C++ Templates: The Complete Guide, Addison Wesley, 2003. Note that Daveed sometimes appears as David.

[52] The C++ Standards Committee is considering relaxing the only within a template rule for these disambiguation hints, and some compilers allow them in non template code already.

[53] See Stroustrup, The C++ Programming Language, 3rd Edition, Addison Wesley, pp. 335 336.

[54] Technically, comparing two pointers that are not inside the same array is undefined behavior, but today s compilers don t complain about this. All the more reason to do it right.

[55] We are indebted to Nathan Myers for this example.

[56] Such as type information encoded in a decorated name.

[57] C++ compilers can introduce names anywhere they want, however. Fortunately, most don t declare names they don t need.

[58] If you re interested in seeing the proposal, it s Core Issue 352.

[59] A reference to the British animated short films by Nick Park featuring Wallace and Gromit.

[60] We discuss vector<bool> in depth in Chapter 7.

[61] Instead of this > you could use any valid qualification, such as Sortable::at( ) or vector<T>::at( ). The point is that it must be qualified.

[62] See also the explanation accompanying PriorityQueue6.cpp in Chapter 7.

[63] Since the forwarding functions are inline, no code for Stack<void*> is generated at all!

[64] Also called Koenig lookup, after Andrew Koenig, who first proposed the technique to the C++ Standards Committee. ADL applies universally, whether templates are involved or not.

[65] From a presentation by Herb Sutter.

[66] A number of compilers use this front end, including Comeau C++.

[67] Also based on an example by Herb Sutter.

[68] In a talk given at The C++ Seminar, Portland, OR, September, 2001.

[69] Another template idiom, mixin inheritance, is covered in Chapter 9.

[70] The fact that char_traits<>::compare( ) may call strcmp( ) in one instance vs. wcscmp( ) in another, for example, is immaterial to the point we make here: the function performed by compare( ) is the same.

[71] Modern C++ Design: Generic Programming and Design Patterns Applied, Addison Wesley, 2001.

[72] C++ Gems, edited by Stan Lippman, SIGS, 1996.

[73] These are technically compile time constants, so you could argue that the identifiers should be all uppercase letters to follow the usual form. We left them lowercased because they are simulations of variables.

[74] In 1966 B hm and Jacopini proved that any language supporting selection and repetition, along with the ability to use an arbitrary number of variables, is equivalent to a Turing machine, which is believed capable of expressing any algorithm.

[75] Czarnecki and Eisenecker, Generative Programming: Methods, Tools, and Applications, Addison Wesley, 2000, p. 417.

[76] There is a much better way to compute powers of integers: the Russian Peasant Algorithm.

[77] Modern C++ Design, pp. 23 26.

[78] You are not allowed to pass object types (other than built ins) to an ellipsis parameter specification, but since we are only asking for its size (a compile time operation), the expression is never actually evaluated at runtime.

[79] A reprint of Todd s original article can be found in Lippman, C++ Gems, SIGS, 1996. It should also be noted that besides retaining mathematical notation and optimized code, expression templates also allow for C++ libraries to incorporate paradigms and mechanisms found in other programming languages, such as lambda expressions. Another example is the fantastic class library Spirit, which is a parser that makes heavy use of expression templates, allowing for (an approximate) EBNF notation directly in C++, resulting in extremely efficient parsers. Visit https://spirit.sourceforge.net/.

[80] See his and Nico s book, C++ Templates, book cited earlier.

[81] Namely, Blitz++ (https://www.oonumerics.org/blitz/), the Matrix Template Library (https://www.osl.iu.edu/research/mtl/), and POOMA (https://www.acl.lanl.gov/pooma/).

[82] We mean vector in the mathematical sense, as a fixed length, one dimensional, numerical array.

[83] Langer and Kreft, C++ Expression Templates, C/C++ Users Journal, March 2003. See also the article on expression templates by Thomas Becker in the June 2003 issue of the same journal (that article was the inspiration for the material in this section).

[84] As explained earlier, you must explicitly instantiate a template only once per program.

[85] Visit https://www.bdsoft.com/tools/stlfilt.html.

[86] Or something that is callable as a function, as you ll see shortly.

[87] This is simply an English rendition of O(n log n), which is the mathematical way of saying that for large n, the number of comparisons grows in direct proportion to the function f(n) = n log n.

[88] Unless you do something ungainly using global variables.

[89] Function objects are also called functors, after a mathematical concept with similar behavior.

[90] The spelling here is adaptor, following the use in the C++ Standard. Elsewhere you will see it spelled adapter when used in the context of design patterns, following the common spelling there. Both spellings are considered acceptable by dictionaries.

[91] There s a complication with different library implementations. If pow( ) has C linkage, meaning its name is not mangled like C++ functions, then this example won t compile. ptr_fun requires a pointer to a normal, overloadable C++ function.

[92] If a compiler were to define string::empty with default arguments (which is allowed), then the expression &string::empty would define a pointer to a member function taking the total number of arguments. Since there is no way for the compiler to provide the extra defaults, there would be a missing argument error when an algorithm applied string::empty via mem_fun_ref.

[93] STLPort, for instance, which comes with version 6 of Borland C++ Builder and the Digital Mars compiler, and is based on SGI STL.

[94] The stable_sort( ) algorithm uses mergesort, which is indeed stable, but tends to run slower than quicksort on average.

[95] Iterators are discussed in more depth in the next chapter.

[96] Algorithms can determine the type of an iterator by reading its tag, discussed in the next chapter.

[97] We re ignoring the copy constructor and assignment operator in this example, since they don t apply.

[98] Without violating any copyright laws, of course.

[99] This would be an example of the State pattern, described in Chapter 10.

[100] Visit https://www.dinkumware.com, https://www.sgi.com/tech/stl, or https://www.stlport.org.

[101] This is about to change, as more smart pointer types are about to be added to the next version of the Standard. For a preliminary look at them, see the smart pointers available at www.boost.org.

[102] The container adaptors, stack, queue, and priority_queue do not support iterators, since they do not behave as sequences from the user s point of view.

[103] It will only work for implementations of vector that use a pointer (a T*) as the iterator type, like STLPort does.

[104] These were actually created to abstract the locale facets away from iostreams so that locale facets could operate on any sequence of characters, not just iostreams. Locales allow iostreams to easily handle culturally different formatting (such as the representation of money).

[105] You will need to provide a char_traits specialization for any other argument type.

[106] We are indebted to Nathan Myers for explaining this.

[107] Singleton is a well known design pattern and is discussed in depth in Chapter 10.

[108] This is another example coached by Nathan Myers.

[109] We revisit multithreading issues in Chapter 11.

[110] This means they depend in some way on a template parameter. See Chapter 5 in the section entitled Name Lookup Issues.

[111] As we explained in Chapter 5, any valid qualification, such as PQV::, will do.

[112] Chuck designed and provided the original reference implementations for bitset and also bitstring, the precursor to vector<bool>, while an active member of the C++ Standards Committee in the early 1990s.

[113] Technically, it is not legal for users to add to the standard namespace, but it is the easiest way to avoid this obscure name lookup problem, and is supported by all the compilers we use.

[114] They will likely appear in the next revision of Standard C++.

[115] Available at https://www.sgi.com/tech/stl.

[116] As we explained earlier, the vector<bool> specialization is also a non STL container to some degree.

[117] With Microsoft s compilers you will have to enable RTTI; it s disabled by default. The command line option to enable it is /GR.

[118] Compilers typically insert a pointer to a class s RTTI table inside its virtual function table.

[119] A dynamic_cast<void*> always gives the address of the full object not a subobject. This will be explained more fully in the next chapter.

[120] This is also true of Java, and other object oriented languages.

[121] These version numbers are internal AT&T numberings.

[122] Even more importantly, we don t want undefined behavior. It is an error for a base class not to have a virtual destructor.

[123] The actual layout is implementation specific.

[124] But not detected as an error. dynamic_cast, however, can solve this problem. See the previous chapter for details.

[125] That is, 5*sizeof(int). Compilers can add arbitrary padding, so the size of an object must be at least as large as the sum of its parts, but can be larger.

[126] We use the term hierarchy because everyone else does, but the graph representing multiple inheritance relationships is in general a directed acyclic graph (DAG), also called a lattice, for obvious reasons.

[127] The presence of these pointers explains why the size of b is much larger than the size of four integers. This is (part of) the cost of virtual base classes. There is also VPTR overhead due to the virtual destructor.

[128] Once again, base classes must have virtual destructors, but most compilers will let this experiment compile.

[129] Note that virtual inheritance is crucial to this example. If Top were not a virtual base class, there would be multiple Top subobjects, and the ambiguity would remain. Dominance with multiple inheritance only comes into play with virtual base classes.

[130] Jerry Schwarz, the author of iostreams, has remarked to both of us on separate occasions that if he had it to do over again, he would probably remove MI from the design of iostreams and use multiple stream buffers and conversion operators instead.

[131] We ve seen this in commercial C++ libraries, at least in some of the early ones.

[132] A phrase coined by Zack Urlocker.

[133] Conveniently, the examples are in C++; unfortunately, the dialect is pre Standard C++ which suffers from the lack of more modern language features like STL containers.

[134] Much of this material was derived from Thinking in Patterns: Problem Solving Techniques using Java, available at www.MindView.net.

[135] For up to date information, visit https://hillside.net/patterns.

[136] Bill Venners name for it; you may see it named differently elsewhere.

[137] The C++ Standard states: No translation unit shall contain more than one definition of any variable, function, class type, enumeration type or template Every program shall contain exactly one definition of every non inline function or object that is used in that program.

[138] This is known as Meyers Singleton, after its creator, Scott Meyers.

[139] Andrei Alexandrescu develops a superior, policy based solution to implementing the Singleton pattern in Modern C++ Design.

[140] For more information, see the article Once is Not Enough by Hyslop and Sutter in the March 2003 issue of CUJ.

[141] #[BT_F4]#Page 235.

[142] See Thinking in C++, Volume 1 for more details about reference counting.

[143]James O. Coplien, Advanced C++ Programming Styles and Idioms, Addison Wesley, 1992.

[144] It differs from Java in that java.util.Observable.notifyObservers( ) doesn t call clearChanged( ) until after notifying all the observers

[145] There is some similarity between inner classes and subroutine closures, which save the reference environment of a function call so it can be reproduced later.

[146] This example existed for a number of years in both C++ and Java on www.MindView.net before it appeared, without attribution, in a recent book by other authors.

[147] The motivation for including Visitor in GoF was probably excessive cleverness. At a workshop, one of the GoF authors told one of us that Visitor was his favorite pattern.

[148] This is true when the system uses time slicing (Windows, for example). Solaris uses a FIFO concurrency model: unless a higher priority thread is awakened the current thread runs until it blocks or terminates. That means that other threads with the same priority don t run until the current one gives up the processor.

[149] Assuming you ve designed it for multiple CPUs. Otherwise, code that seems to work fine on a time sliced single processor system can fail when moved to multiple CPU system, since the additional CPUs can reveal problems that a one CPU system does not.

[150] Much of this chapter began as a translation from the Concurrency chapter in Thinking in Java, 3rd edition, Prentice Hall 2003, although it has changed very significantly in the process.

[151] This can be significant. Usually only a small part of a function needs to be guarded. Putting the guard at the function entry point can often make the critical section longer than it needs to be.

[152] This is an oversimplification. Sometimes even when it seems like an atomic operation should be safe, it may not be, so you must be very careful when deciding that you can get away without synchronization. Removing synchronization is often a sign of premature optimization things that can cause you a lot of trouble without gaining much. Or anything.

[153] Atomicity isn t the only issue. On multiprocessor systems visibility is much more of an issue than on single processor systems. Changes made by one thread, even if they re atomic in the sense of not being interruptible, might not be visible to other threads (the changes might be temporarily stored in a local processor cache, for example), so different threads will have a different view of the application s state. The synchronization mechanism forces changes by one thread on a multiprocessor system to be visible across the application, whereas without synchronization it s indeterminate when changes become visible.

[154] However, exceptions are never delivered asynchronously in ZThreads. Thus, there is no danger of something aborting mid instruction/function call. And as long as you use the Guard template to acquire mutexes, the mutexes will be automatically released if an exception is thrown.

[155] Actually, sleep( ) only provides a minimum delay, not a guaranteed delay, so it s possible (although improbable) that the sleep(1100) will wake up before the sleep(1000).

[156] There is nothing in the C++ Standard that says that interruptions can t occur during IO operations. However, most implementations don t support it.

[157] Note that, although it s unlikely, the call to t.interrupt( ) could actually happen before the call to blocked.f( ).

[158] This is in contrast to Java, where you must hold the lock in order to call notify( ) (Java s version of signal( )). Although Posix threads, on which the ZThread library is loosely based, do not require that you hold the lock in order to call signal( ) or broadcast( ), it is often recommended.

[159] On some platforms there s a third way to come out of a wait( ), the so called spurious wakeup. A spurious wakeup essentially means that a thread may prematurely stop blocking (while waiting on a condition variable or semaphore) without being prompted by a signal( ) or broadcast( ). The thread just wakes up, seemingly by itself. Spurious wakeups exist because implementing POSIX threads, or the equivalent, isn t always as straightforward as it should be on some platforms. By allowing spurious wakeups the job of building a library like pthreads is easier for those platforms. Spurious wakeups do not occur in ZThreads, because the library compensates for and hides these issues from the user.

[160] Note that if the readers stop for some reason, the writers will keep on writing until the system runs out of memory. If this is an issue with your program you can add a maximum allowable element count, and writers should then block if the queue is full.

[161] In particular, refer to the earlier footnote in this chapter on multiprocessors and visibility.

[162] At the time of this writing, Cygwin (www.cygwin.com) was undergoing changes and improvements to its threading support, but we were still unable to observe deadlocking behavior with this program under the available version of Cygwin. The program deadlocked quickly under, for example, Linux.

Thinking in C++ Vol 2 - Practical Programming
Prev Home Next

 
 
   Reproduced courtesy of Bruce Eckel, MindView, Inc. Design by Interspire