4. A Simple Example
• Hello World
#include <iostream>
using namespace std;
int main()
{
cout << "Hello! World!n";
cout << “Hello! C++!n";
return 0;
}
5. Namespace
• When programs grow too large, it is very difficult to manage the names of
variables, functions, classes. It is better to use namespace to resolve the
troubles.
• Namespace is like a container. Namespaces allow to group entities like
classes, objects and functions under a name. This way the global scope
can be divided in "sub-scopes", each one with its own name. For example,
variables of the same name will not conflict with each other when they
are in distinct namespaces.
• The format of namespaces is:
namespace identifier
{
entities;
}
6. Namespace Example
#include <iostream>
using namespace std;
namespace integer
{
int x = 5;
int y = 10;
}
namespace floating
{
double x = 3.67;
double y = 2e-1;
}
int main () {
using integer::x;
using floating::y;
cout << x << endl;
cout << y << endl;
cout << floating::y << endl;
cout << integer::x << endl;
return 0;
}
Please find the answer!!
Do you have other ways of implementing
this?
7. int a; float mynumber;
Variables & Data Types
• Declaration of variables
– Type
– Identifier
• A sequence of one or more letters, digits or underscore
characters (_)
• Have to begin with a letter or underscore characters (_)
• Cannot match any reserved keywords of the C++
language
– catch, char, class, const etc
int a;
float mynumber;
8. Types
Name
Description
Size*
Range*
char
Character or small integer.
1byte
signed: -128 to 127
unsigned: 0 to 255
short int (short)
Short Integer.
2bytes
signed: -32768 to 32767
unsigned: 0 to 65535
int
Integer.
4bytes
signed: -2147483648 to
2147483647
unsigned: 0 to 4294967295
long int (long)
Long integer.
4bytes
signed: -2147483648 to
2147483647
unsigned: 0 to 4294967295
bool
Boolean value. It can take one of
1byte
two values: true or false.
true or false
float
Floating point number.
4bytes
+/- 3.4e +/- 38 (~7 digits)
double
Double precision floating point
number.
8bytes
+/- 1.7e +/- 308 (~15 digits)
long double
Long double precision floating
point number.
8bytes
+/- 1.7e +/- 308 (~15 digits)
wchar_t
Wide character.
2 or 4 bytes
1 wide character
12. Basic Input and Output
• Standard Output (cout)
– cout << "Output sentence";
– cout << “x” << “=” << x << endl;
• Standard Input (cin)
– cin >> age;
– cin >> a >> b;
• cin and strings
– cin extraction stops reading as soon as any blank space
character is encountered.
– getline (cin, mystr) can also be used such that a line can be read
at a time;
• stringstream
– stringstream(mystr) >> myint;
13. Basic Input and Output (Cont’)
Io.cpp
//io.cpp
#include <iostream>
using namespace std;
int main()
{
int a, b;
cout << "input a & b: ";
cin >> a >> b;
cout << "a + b = " << a + b << endl;
return 0;
}
14. Program Flow Control
• Conditional structure
– if, else
• Iteration structures (loops)
– while
– do-while
– for
• Jump statements
– break
– continue
– goto
• The selective structure
– switch
15. Program Flow Control (Cont’)
//flow.cpp
#include <iostream>
using namespace std;
Flow.cpp
int main()
{
int a, b;
int c = 0;
int sum = 0;
cout << "input a & b: ";
cin >> a >> b;
if(a == b)
cout << "a == b" << endl;
else
cout << "a != b" << endl;
for(int i=0;i<a;i++)
sum += i;
cout << "sum = " << sum << endl;
16. Program Flow Control (Cont’)
while(1)
{
cout << "c = " << c << endl;
Flow.cpp
switch(c)
{
case 0:
c ++;
break;
case 1:
c ++;
case 2:
c ++;
break;
}
if(c < 2)
continue;
else
break;
cout << "not excute" << endl;
}
return 0;
}
17. Functions
• A group of statements that are executed when
the function is called from some point of the
program.
• Format
– type name ( parameter1, parameter2, ...) {
statements } int addition (int a, int b)
{
int r;
r = a + b;
return (r);
}
result = addition(a, b)
18. Overloading
• In C++, If more than one definitions for a function name or an operator in
the same scope are specified, that function name or operator is
overloaded.
• In such cases, the compiler determines the most appropriate definition by
comparing the argument types specified in the definitions to call the
function or operator. Hence, we can the same name to more than one
functions if those functions have either a different number of parameters
or different types in their parameters.
int addition (int a, int b);
float addition (float a, float b);
int ir, ia, ib;
float fr, fa, fb;
ir = addition(ia, ib);
fr = addition(fa, fb);
19. Operators about overloading
• You can overload any of the following operators:
– +, -, *, /, %, ^, &, |, ~ ,! =, <, >, +=, -=, *=, /=, %= ,^=, &=, |=, <<, >>, <<=,
>>=, ==, !=, <=, >=, &&, ||, ++, -- , ->*, -> ,( ), [ ], new, delete, new[]
and delete[]
– In the above, () is the function call operator and [] is the subscript
operator.
• You can overload both the unary and binary forms of the following
operators: +, -, *, & .
• You cannot overload the following operators: ., .*, :: and ?:.
• You cannot overload the preprocessor symbols such as # and ##.
20. Compound Data Types
• Arrays
– int a[10];
– int b[10][10];
a
0
1
a[0] == 0;
2
…
• Character Sequences
– char c*+ = “test sequence”;
21. Compound Data Types (Cont’)
• Pointers
– int a = 10;
– int *p_a = &a;
– int **p_p_a = &p_a;
a
*p_a == 10;
**p_p_a == 10;
10
52
56
60
p_a
56
100
p_p_a
104
108
104
22. Compound Data Types (Cont’)
•
Dynamic Memory
– 1D array
• int *a = new int[10];
• delete[] a;
– 2D array
• int **b = new int*[10];
• for(int i=0;i<10;i++) b[i] = new int[10];
• for(int i=0;i<10;i++) delete[] b[i];
• delete[] b;
b
0
1
.
.
.
0
1
2
0
1
2
.
.
.
23. Compound Data Types (Cont’)
• Data Structures
struct example {
int a;
float b;
char c[4];
};
example tmp;
tmp.a = 10;
tmp.b = 3.14;
tmp.c*0+ = ‘a’;
24. Class
• An expanded concept of conventional data structure. Instead
of holding only data, it can also hold both functions.
• An object is an instantiation of a class. In terms of variables, a
class would be regarded as one of types, and an object would
be regarded as the corresponding variable.
• All data and functions in a class is called members of the class.
• Format:
class class_name {
access_specifier_1:
member1;
access_specifier_2:
member2; ...
} object_name;
25. Class Example
#include <iostream>
using namespace std;
class CRectangle {
private:
int *width, *height;
public:
CRectangle ();
CRectangle (int,int);
~CRectangle ();
int area () {return (*width * *height);}
friend CRectangle duplicate (CRectangle);
};
CRectangle::CRectangle (){
width = new int;
height = new int;
}
CRectangle::CRectangle (int a, int b){
width = new int;
height = new int;
*width = a;
*height = b;
}
CRectangle::~CRectangle () {
delete width;
delete height;
}
26. Class Example
CRectangle duplicate (CRectangle rectparam) {
CRectangle rectres;
*(rectres.width) = (*(rectparam.width))*2;
*(rectres.height) = (*(rectparam.height))*2;
return (rectres);
}
int main () {
CRectangle rect(2, 3);
Crectangle rectb;
rectb = duplicate (rect);
cout << rectb.area();
return 0;
}
27. Class (Cont’)
• Access specifier
– public
• members of a class that are accessible from anywhere
where the object is visible.
– private
• members of a class that are accessible only from within
other members of the same class or from their friends.
– protected
• Members of a class that are accessible from members
of their same class and from their friends, but also from
members of their derived classes.
28. Class (Cont’)
• Constructor
– It is called whenever a new object of this class is
created.
• Destructor
– It is called when an object is to be destroyed,
• if its scope of existence has finished (for example, if it
was defined as a local object within a function and the
function ends.)
• if it is an object dynamically assigned and then
released using the operator delete.
29. Inheritance
• Inheritance allows to create classes which are
derived from other classes so that they can
automatically include some of its "parent's"
members, plus its own members.
30. Inheritance example
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b) { width=a; height=b;}
};
class CRectangle: public CPolygon {
public:
int area () { return (width * height); }
};
31. Inheritance (Cont’)
• The different access types according to who
can access them in the following way
Access
public
protected
private
members of the
same class
yes
yes
yes
members of
derived classes
yes
yes
no
not members
yes
no
no
32. Virtual Member
• A member of a class that can be redefined in
its derived classes is called a virtual member.
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b) { width=a; height=b;}
virtual int area() {return 0;}
};
class CRectangle: public CPolygon {
public:
int area () { return (width * height); }
};
33. Virtual Member (Cont’)
• Pure virtual member
– A member of a class that must be redefined in its
derived classes is called a pure virtual member.
class CPolygon {
protected:
int width, height;
public:
void set_values (int a, int b) { width=a; height=b;}
virtual int area() = 0;
};
class CRectangle: public CPolygon {
public:
int area () { return (width * height); }
};
34. Template
• Function templates
– It is about the fact that special functions that can
operate with generic types.
– One can create a function template whose
functionality can be adapted to more than one
type or classes.
– Format:
• template <class identifier> function_declaration;
• template <typename identifier> function_declaration;
36. Template (Cont’)
• Class templates
– A class having members that use template
parameters as their types.
– Example
template <class T>
class mypair {
T values [2];
public:
mypair (T first, T second)
{ values[0]=first; values[1]=second; }
};
mypair<int> myobject (115, 36);
37. Template (Cont’)
• Non-type parameters for templates
– Templates can have regular type parameters
– Example
template <class T, int N>
class mysequence {
T memblock [N];
public:
void setmember (int x, T value);
T getmember (int x);
};
mysequence <double,5> myfloats;
template <class T=char, int N=10> class mysequence {..};
38. Reference
• C++ Language Tutorial
– http://www.cplusplus.com/doc/tutorial/
• XL C/C++ V8.0
– http://publib.boulder.ibm.com/infocenter/comph
elp/v8v101/index.jsp?topic=/com.ibm.xlcpp8a.do
c/language/ref/overl.htm
• C++ 學習筆記
– http://caterpillar.onlyfun.net/Gossip/CppGossip/C
ppGossip.html
40. Process
• In UNIX, Process is a program which has a
independent memory space and execute
independently. No matter it is a system task or
a user task, it is finished by respective Process.
• In UNIX, every process has a unique id called
process id (pid).
• Each process is created by its parent process.
After finishing its task, it should release all
occupied system resource and exit.
41. Process (Cont’)
• fork-and-exec is the
execution mode of all
processes in UNIX.
• When the system is
boot up, the first
executed process is
init and its pid is 1.
• Then init executes
each process through
fork-and-exec.
42. Process (Cont’)
• Kill:Kill a process by number (-SIGNAL: send a signal to a
process specified by its pid)
• killall:Send a signal to a process by name
• ps:Used to report the status of one or more processes. (aux: list every process)
• pstree:Display the tree of running processes. (-Aup: list
user and pid, print using ASCII)
• top:Displays the processes that are using the most CPU
resources. (-u username)
• nice/renice:set priority of a process (max -20 ~ min 19)
– only superuser can set -20~-1
– normal users can only lower its priority (0~19)
43. Process Programming
• fork()
– It is the only way a new process can be created by
Unix kernel.
– It is called once, returns twice.
– Returns
• 0 in child, process ID of child in parent, and -1 on error.
– Both child and parent continue their executing with
the instruction that follows the call to fork()
– It doesn't perform a complete copy of parent's data,
stack and heap. It's shared by both and have the
protection changed by kernel to read-only. It's
COW(copy-on-write).
44. Process Programming (Cont’)
• The differences between parent/child
– the return value from fork()
– the process IDs, parent IDs
– the child's tms_utime, tms_stime, tms_cutime,
tms_ustime are set to 0
– file locks not inherited by the child
45. Process Programming (Cont’)
Fork.c
//fork.c
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int glob = 6;
char buf[] = "a write to stdoutn";
int main()
{
int var;
pid_t pid;
var = 88;
if(write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf) - 1){
printf("write error");
exit(1);
}
46. Process Programming (Cont’)
printf("before forkn");
if( (pid = fork()) < 0){
printf("fork error");
exit(1);
} else if (pid == 0){ //this is child
glob++;
var++;
}else
sleep(2);
//this is parent
Fork.c
printf("pid = %d, glob = %d, var = %dn", getpid(), glob, var);
exit(0);
}
47. Process Programming (Cont’)
Forkwice.c
//forkwice.c
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t pid;
if( (pid = fork()) < 0){
printf("fork error");
exit(1);
} else if (pid == 0){ //this is first child
if( (pid = fork()) < 0){
printf("fork error");
exit(1);
}else if (pid > 0)
exit(0); //parent from second fork == first child
48. Process Programming (Cont’)
//now we're the second child, our parent becomes init
sleep(1);
printf("second child, parent pid = %dn", getppid());
exit(0);
Forkwice.c
}
//original parent, it waits
if(waitpid(pid, NULL, 0) != pid){ //wait for first child
printf("waitpid error");
exit(1);
}
//note that the shell prints its prompt when the
//original process terminates, which is before
// the second child prints its parent process ID
exit(0);
}
49. Process Programming (Cont’)
• wait() and waitpid()
– block if all of its children are running
– return immediately with the term status of a child (if a
child has terminated)
• Differences:
– wait can block the caller until a child process
terminates.
– waitpid has an option that prevents it from blocking.
– waitpid has a number of options that control which
process it waits for.
50. Process Programming (Cont’)
Wait.c
//wait.c
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int status;
if( (pid = fork()) < 0){
printf("fork error");
exit(1);
} else if (pid == 0){ //this is child
//
exit(7); //normal
abort(); //generates SIGABRT
//
status /= 0; //generates SIGFPE
}
51. Process Programming (Cont’)
//this is parant
if(wait(&status) != pid){
printf("wait error");
exit(1);
}
// print status
if(WIFEXITED(status))
printf("normal termination, exit status = %dn", WEXITSTATUS(status));
else if (WIFSIGNALED(status))
printf("abnormal termination, signal number = %dn", WTERMSIG(status));
else if (WIFSTOPPED(status))
printf("child stopped, signal number= %dn", WSTOPSIG(status));
Wait.c
exit(0);
}
52. Process Programming (Cont’)
• exec:
– When a process calls exec functions, the process is
completely replaced by the new program.
– The process ID doesn't change: exec merely replaces the
current process(its text, data, heap, and stack segments).
• Family
– int execl(const char *path, const char *arg, ...)
– int execlp(const char *file, const char *arg, ...)
– int execle(const char *path, const char *arg , ..., char *
const envp[])
– int execv(const char *path, char *const argv[])
– int execvp(const char *file, char *const argv[])
57. Thread
• A thread (sometimes known as an execution
context or a lightweight process) is a single
sequential flow of control within a process.
• A typical UNIX process have a single thread of
control.
– Each process is doing only one thing at a time.
• Multithreading means that it can have more
than one thread of control.
– Each process can do many things at a time.
58. Benefits
1. Simplify a design that need to deal with
asynchronous events.
2. Resource sharing
3. Improve SOME program throughput
– E.g. blockable program
4. Improve interactive time
59. Resources of thread
• Proprietary
– Identity
• Thread ID
–
–
–
–
–
–
A set of Registers
A Stack
A scheduling priority and policy
Signal mask
Errno variable
Thread-specific data
–
–
–
–
Text of executable program
Program’s global and heap memory
Stacks
File descriptors
• Shared
60. Thread Standard
• Defined in IEEE POSIX.1-2001
• POSIX Thread or pthread
• How to detect?
– #ifdef _POSIX_THREADS
– sysconf( _SC_THREADS )
61. Thread Identification
• Process ID is unique in the system; thread ID is
unique in the process
• Must use function to manipulate thread ID
• Q: Can we print thread ID directly?
– Ans: NO
#include <pthread.h>
int pthread_equal( pthread_t tid1, pthread_t tid2 )
Returns: nonzero if equal, 0 otherwise
pthread_t pthread_self()
62. Thread Creation
• pthread_create()
#include <pthread.h>
int pthread_create( pthread_t * restrict tidp,
const pthread_attr_t* restrict attr,
void * (*start_rtn)(void),
void* restrict arg )
Return: 0 if OK, error number on failure
• Return error code and don’t set errno when failure
• No guarantee on the running order of the threads created
and the threads creating
63. Example
• See print_id.c
• -D_REENTRANT –lpthread
Q&A:
1. Why sleep( 1 ) is needed?
2. Why pthread_self() instrad of ntid?
66. Other Platforms
• Solaris 9
main thread: pid 7225 tid 1 (0x1)
new thread: pid 7225 tid 4 (0x4)
• FreeBSD 5.2.1
main thread: pid 14954 tid 134529024 (0x804c000)
new thread: pid 14954 tid 134530048 (0x804c400)
• MacOS Darwin 7.4.0
main thread: pid 779 tid 2684396012 (0xa000a1ec)
new thread: pid 779 tid 25166336 (0x1800200)
• Linux 2.4.22
new thread: pid 6628 tid 1026 (0x402)
main thread: pid 6626 tid 1024 (0x400)
67. Thread Termination
• How can a thread exit?
1. Voluntary
1. Return from the start routine
2. Call pthread_exit
2. Involuntary
1. Canceled by another thread in the same process
68. Thread Termination - Voluntary
• Set/Get return value
#include <pthread.h>
void pthread_exit( void* rval_ptr );
int pthread_join( pthread_t thread,
void** rval_ptr );
Return: 0 if OK, error number on failure
69. Thread Termination - Voluntary
• Example
– See get_rtnv.c
• Be careful of your Memory Usage
– See get_smem_rtnv.c
74. Thread Synchronization
• Threads share the same
memory space.
• Modification takes
more than one memory
cycle.
– E.g. Memory read is
interleaved between the
memory write cycles.
76. Mutex
• Mutual-exclusive
• A lock set (lock) before accessing a shared
resource and releaseed (unlock) when a job is
done.
– Only one thread will proceed at a time.
#include <pthread.h>
pthread_mutex_t
PTHREAD_MUTEX_INITIALIZER
int pthread_mutex_init( pthread_mutex_t* restrict mutex,
const pthread_mutexattr_t* restrict attr )
int pthread_mutex_destroy( pthread_mutex_t* mutex )
Return: 0 if OK, error number on failure
77. Mutex
• Mutex operation
#include <pthread.h>
int pthread_mutex_lock( pthread_mutex_t* restrict mutex )
int pthread_mutex_unlock( pthread_mutex_t* mutex )
int pthread_mutex_trylock( pthread_mutex_t* mutex )
Return: 0 if OK, error number on failure
81. Mutex
• Deadlock
– A process/thread is blocked on a resource request
that can never be satisfied.
• A thread will be deadlocked if it tries to lock
the same mutex twice.
• Some threads may be deadlocked because
each thread needs a resource which is locked
by others.
82. Reference
• The Single UNIX® Specification, Version 2
– http://www.opengroup.org/pubs/online/7908799
/
• The Open Group Base Specifications Issue 6
IEEE Std 1003.1, 2004 Edition
– http://www.opengroup.org/onlinepubs/00969539
9/
• Cpp Reference
– http://www.cppreference.com