SlideShare una empresa de Scribd logo
1 de 82
Brief Review to C++ / Process /
Thread
石宗胤, 周惟中, 蘇文鈺
2009/09/14
Outline
• C++
• Process
• Thread
C++
A Simple Example
• Hello World
#include <iostream>
using namespace std;
int main()
{
cout << "Hello! World!n";
cout << “Hello! C++!n";
return 0;
}
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;
}
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?
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;
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
Literal Constant
• Integer Numerals
– 75, 75u, 75l, 75ul, 0113, 0x4b

• Floating-Point Numerals
– 3.1415, 6.02e23, 1.6e-19, 3.0, 3.1415l, 6.02e23f

• Characters
– ‘x’, ‘n’

• Strings
– "Hello world“, “onentwonthree”

• Boolean Values
– true, false
Operators
Level
1

Operator
::

Description
scope

Grouping
Left-to-right

2

() [] . -> ++ -- dynamic_cast static_cast
reinterpret_cast const_cast typeid

postfix

Left-to-right

4

++ -- ~ ! sizeof new delete
*&
+(type)

unary (prefix)
indirection and reference (pointers)
unary sign operator
type casting

5

.* ->*

pointer-to-member

Left-to-right

6
7
8
9
10
11
12
13
14
15
16

*/%
+<< >>
< > <= >=
== !=
&
^
|
&&
||
?:

multiplicative
additive
shift
relational
equality
bitwise AND
bitwise XOR
bitwise OR
logical AND
logical OR
conditional

Left-to-right
Left-to-right
Left-to-right
Left-to-right
Left-to-right
Left-to-right
Left-to-right
Left-to-right
Left-to-right
Left-to-right
Right-to-left

17

= *= /= %= += -= >>= <<= &= ^= |=

assignment

Right-to-left

18

,

comma

Left-to-right

3

Right-to-left
Right-to-left
Operators (Cont’)
• Grouping
– Left to right
• a+b+c
– (a + b) + c

– Right to left
• a += b += c
– b=b+c
– a=a+b
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;
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;
}
Program Flow Control
• Conditional structure
– if, else

• Iteration structures (loops)
– while
– do-while
– for

• Jump statements
– break
– continue
– goto

• The selective structure
– switch
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;
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;

}
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)
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);
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 ##.
Compound Data Types
• Arrays
– int a[10];
– int b[10][10];
a

0

1

a[0] == 0;
2

…

• Character Sequences
– char c*+ = “test sequence”;
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
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

.
.
.
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’;
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;
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;
}
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;
}
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.
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.
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.
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); }
};
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
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); }
};
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); }
};
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;
Template (Cont’)
– Example
template <class myType>
myType GetMax (myType a, myType b) {
return (a>b?a:b);
}
int x,y;
GetMax <int> (x,y);
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);
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 {..};
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
Process
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.
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.
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)
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).
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
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);
}
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);
}
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
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);
}
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.
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
}
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);

}
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[])
Process Programming (Cont’)
Exe.c

//exe.c
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
char *env_init[] = { "USER=unknown", "PATH=/tmp", NULL};
int main()
{
pid_t pid;
if( (pid = fork()) < 0 ){
printf("fork error");
exit(1);
}else if (pid == 0){ //child
///*
//specify pathname, specify environment
if(execle("/home/starryalley/Desktop/Linux_process_signal/example/echoall",
"echoall", "arg1", "arg 2", "my arg 3", (char*)0,
env_init) < 0){
printf("execle error");
exit(1);
}
//*/
Process Programming (Cont’)
Exe.c

/*
//specify filename, inherit environment
if(execlp("./echoall",
"echoall", "only 1 arg", (char*)0) < 0){
printf("execlp error");
exit(1);
}
*/
}
if(waitpid(pid, NULL, 0) < 0){
printf("wait error");
exit(1);
}
}
Thread
Outline
• Thread
– Introduction
– Identification
– Creation
– Termination

• Thread Synchronization
– Mutex
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.
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
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
Thread Standard
• Defined in IEEE POSIX.1-2001
• POSIX Thread or pthread
• How to detect?
– #ifdef _POSIX_THREADS
– sysconf( _SC_THREADS )
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()
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
Example
• See print_id.c
• -D_REENTRANT –lpthread
Q&A:
1. Why sleep( 1 ) is needed?
2. Why pthread_self() instrad of ntid?
Example(Cont’)
Print_id.c

//print_id.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <pthread.h>
pthread_t ntid;
void printids( const char* s )
{
pid_t
pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf( "%s pid %u tid %u (0x%x)n", s, (unsigned int) pid
, (unsigned int) tid, (unsigned int) tid );
}
Example(Cont’)
Print_id.c

void* thr_fn( void* arg )
{
printids( "New thread: " );
return ((void*) 0);
}
int main()
{
int err = pthread_create( &ntid, NULL, thr_fn, NULL );
if ( 0 != err ) {
fprintf( stderr, "can't create thread: %sn", strerror( err ) );
}
printids( "main thread:" );
sleep( 1 );
return 0;
}
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)
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
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
Thread Termination - Voluntary
• Example
– See get_rtnv.c

• Be careful of your Memory Usage
– See get_smem_rtnv.c
Example
Get_rtnv.c

//get_rtnv.c
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <pthread.h>
void* thr_fn1( void* arg )
{
printf( "thread 1 returningn" );
return ((void*) 1);
}
void* thr_fn2( void* arg )
{
printf( "thread 2 returningn" );
return ((void*) 2);
}
Example(Cont’)
Get_rtnv.c

int main()
{
int
err;
pthread_t tid1, tid2;
void*
tret;
err = pthread_create( &tid1, NULL, thr_fn1, NULL );

if ( 0 != err ) {
fprintf( stderr, "Can't create thread 1: %sn", strerror( err ) );
return 1;
}
err = pthread_create( &tid2, NULL, thr_fn2, NULL );
if ( 0 != err ) {
fprintf( stderr, "Can't create thread 2: %sn", strerror( err ) );
return 1;
}
Get_rtnv.c

Example(Cont’)
err = pthread_join( tid1, &tret );
if ( 0 != err ) {
fprintf( stderr, "Can't join with thread 1: %sn", strerror( err ) );
return 1;
}
printf( "thread 1 exit code %dn", (int) tret );
err = pthread_join( tid2, &tret );
if ( 0 != err ) {
fprintf( stderr, "Can't join with thread 2: %sn", strerror( err ) );
return 1;
}
printf( "thread 2 exit code %dn", (int) tret );
return 0;

}
Summary
Process
Primitive

Thread
Primitive

Description

fork

pthread_create

Create a flow of control

exit

pthread_exit

Exit from an existing flow of control

waitpid

pthread_join

Get exit status from flow of control
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.
Thread Synchronization
• Solution
– Lock the critical sections
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
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
Example Mutex
Mutex_cnt.c

//mutex_cnt.c
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
struct foo {
int
f_count;
pthread_mutex_t f_lock;
};
struct foo* foo_alloc()
{
struct foo* fp;
if ( (fp = malloc(sizeof( struct foo ))) != NULL ) {
fp->f_count = 1;
if ( pthread_mutex_init( &fp->f_lock, NULL ) != 0 ) {
free( fp );
return (NULL);
}
}
return (fp);
}
Example Mutex(Cont’)
Mutex_cnt.c

void foo_hold( struct foo* fp )
{
pthread_mutex_lock( &fp->f_lock );
fp->f_count++;
pthread_mutex_unlock( &fp->f_lock );
}
void foo_rele( struct foo* fp )
{
pthread_mutex_lock( &fp->f_lock );
if ( --fp->f_count == 0 ) {
pthread_mutex_unlock( &fp->f_lock );
pthread_mutex_destroy( &fp->f_lock );
free( fp );
}
else
pthread_mutex_unlock( &fp->f_lock );
}
Example Mutex(Cont’)
Mutex_cnt.c

void* thr_fn( void* arg )
{
struct foo *fp = (struct foo *)arg;
foo_hold(fp);
printf("foo count = %dn", fp->f_count);
foo_rele(fp);
pthread_exit( (void*) 0 );

}
int main()
{
struct foo *fp = foo_alloc();
pthread_t tid1, tid2;
int i;
pthread_create( &tid1, NULL, thr_fn, fp);
pthread_create( &tid2, NULL, thr_fn, fp);
pthread_join( tid1, (void*) &i );
pthread_join( tid2, (void*) &i );
foo_rele(fp);
return 0;

}
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.
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

Más contenido relacionado

Destacado

Track c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eveTrack c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -evechiportal
 
Top five reasons why every DV engineer will love the latest systemverilog 201...
Top five reasons why every DV engineer will love the latest systemverilog 201...Top five reasons why every DV engineer will love the latest systemverilog 201...
Top five reasons why every DV engineer will love the latest systemverilog 201...Srinivasan Venkataramanan
 
A Systematic Approach to Creating Behavioral Models (white paper) v1.0
A Systematic Approach to Creating Behavioral Models (white paper) v1.0A Systematic Approach to Creating Behavioral Models (white paper) v1.0
A Systematic Approach to Creating Behavioral Models (white paper) v1.0Robert O. Peruzzi, PhD, PE, DFE
 
SystemVerilog Assertions (SVA) in the Design/Verification Process
SystemVerilog Assertions (SVA) in the Design/Verification ProcessSystemVerilog Assertions (SVA) in the Design/Verification Process
SystemVerilog Assertions (SVA) in the Design/Verification ProcessDVClub
 
How to Connect SystemVerilog with Octave
How to Connect SystemVerilog with OctaveHow to Connect SystemVerilog with Octave
How to Connect SystemVerilog with OctaveAmiq Consulting
 
UVM Ral model usage
UVM Ral model usageUVM Ral model usage
UVM Ral model usageParth Pandya
 
UVM Update: Register Package
UVM Update: Register PackageUVM Update: Register Package
UVM Update: Register PackageDVClub
 
SystemVerilog Assertions verification with SVAUnit - DVCon US 2016 Tutorial
SystemVerilog Assertions verification with SVAUnit - DVCon US 2016 TutorialSystemVerilog Assertions verification with SVAUnit - DVCon US 2016 Tutorial
SystemVerilog Assertions verification with SVAUnit - DVCon US 2016 TutorialAmiq Consulting
 
Design and Implementation of an Advanced DMA Controller on AMBA-Based SoC
Design and Implementation of an Advanced DMA Controller on AMBA-Based SoCDesign and Implementation of an Advanced DMA Controller on AMBA-Based SoC
Design and Implementation of an Advanced DMA Controller on AMBA-Based SoCRabindranath Tagore University, Bhopal
 

Destacado (19)

Esl basics
Esl basicsEsl basics
Esl basics
 
SystemC Ports
SystemC PortsSystemC Ports
SystemC Ports
 
MixedSignal UVM Demo CDNLive
MixedSignal UVM Demo CDNLiveMixedSignal UVM Demo CDNLive
MixedSignal UVM Demo CDNLive
 
Track c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eveTrack c-High speed transaction-based hw-sw coverification -eve
Track c-High speed transaction-based hw-sw coverification -eve
 
Top five reasons why every DV engineer will love the latest systemverilog 201...
Top five reasons why every DV engineer will love the latest systemverilog 201...Top five reasons why every DV engineer will love the latest systemverilog 201...
Top five reasons why every DV engineer will love the latest systemverilog 201...
 
A Systematic Approach to Creating Behavioral Models (white paper) v1.0
A Systematic Approach to Creating Behavioral Models (white paper) v1.0A Systematic Approach to Creating Behavioral Models (white paper) v1.0
A Systematic Approach to Creating Behavioral Models (white paper) v1.0
 
SystemVerilog Assertions (SVA) in the Design/Verification Process
SystemVerilog Assertions (SVA) in the Design/Verification ProcessSystemVerilog Assertions (SVA) in the Design/Verification Process
SystemVerilog Assertions (SVA) in the Design/Verification Process
 
How to Connect SystemVerilog with Octave
How to Connect SystemVerilog with OctaveHow to Connect SystemVerilog with Octave
How to Connect SystemVerilog with Octave
 
UVM Ral model usage
UVM Ral model usageUVM Ral model usage
UVM Ral model usage
 
UVM Update: Register Package
UVM Update: Register PackageUVM Update: Register Package
UVM Update: Register Package
 
SystemVerilog Assertions verification with SVAUnit - DVCon US 2016 Tutorial
SystemVerilog Assertions verification with SVAUnit - DVCon US 2016 TutorialSystemVerilog Assertions verification with SVAUnit - DVCon US 2016 Tutorial
SystemVerilog Assertions verification with SVAUnit - DVCon US 2016 Tutorial
 
stack
stackstack
stack
 
Design and Implementation of an Advanced DMA Controller on AMBA-Based SoC
Design and Implementation of an Advanced DMA Controller on AMBA-Based SoCDesign and Implementation of an Advanced DMA Controller on AMBA-Based SoC
Design and Implementation of an Advanced DMA Controller on AMBA-Based SoC
 
Queue
QueueQueue
Queue
 
Tree
TreeTree
Tree
 
Queue
QueueQueue
Queue
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 
Queuing Theory
Queuing TheoryQueuing Theory
Queuing Theory
 
SystemC
SystemCSystemC
SystemC
 

Similar a C++ process new

2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloadingkinan keshkeh
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overviewTAlha MAlik
 
Learning python
Learning pythonLearning python
Learning pythonFraboni Ec
 
Learning python
Learning pythonLearning python
Learning pythonJames Wong
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptxNelyJay
 
C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8Christian Nagel
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operatorsraksharao
 
2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++kinan keshkeh
 
Modern C++ Lunch and Learn
Modern C++ Lunch and LearnModern C++ Lunch and Learn
Modern C++ Lunch and LearnPaul Irwin
 

Similar a C++ process new (20)

2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading2 BytesC++ course_2014_c3_ function basics&parameters and overloading
2 BytesC++ course_2014_c3_ function basics&parameters and overloading
 
Cs1123 3 c++ overview
Cs1123 3 c++ overviewCs1123 3 c++ overview
Cs1123 3 c++ overview
 
C
CC
C
 
Learning python
Learning pythonLearning python
Learning python
 
Learning python
Learning pythonLearning python
Learning python
 
Learning python
Learning pythonLearning python
Learning python
 
Learning python
Learning pythonLearning python
Learning python
 
Learning python
Learning pythonLearning python
Learning python
 
Learning python
Learning pythonLearning python
Learning python
 
Learning python
Learning pythonLearning python
Learning python
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Lecture 9_Classes.pptx
Lecture 9_Classes.pptxLecture 9_Classes.pptx
Lecture 9_Classes.pptx
 
C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8C# 7.x What's new and what's coming with C# 8
C# 7.x What's new and what's coming with C# 8
 
CP 04.pptx
CP 04.pptxCP 04.pptx
CP 04.pptx
 
Modern C++
Modern C++Modern C++
Modern C++
 
Data types and Operators
Data types and OperatorsData types and Operators
Data types and Operators
 
2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++2 BytesC++ course_2014_c1_basicsc++
2 BytesC++ course_2014_c1_basicsc++
 
4.ArraysInC.pdf
4.ArraysInC.pdf4.ArraysInC.pdf
4.ArraysInC.pdf
 
Modern C++ Lunch and Learn
Modern C++ Lunch and LearnModern C++ Lunch and Learn
Modern C++ Lunch and Learn
 

Último

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 

Último (20)

Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 

C++ process new

  • 1. Brief Review to C++ / Process / Thread 石宗胤, 周惟中, 蘇文鈺 2009/09/14
  • 3. C++
  • 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
  • 9. Literal Constant • Integer Numerals – 75, 75u, 75l, 75ul, 0113, 0x4b • Floating-Point Numerals – 3.1415, 6.02e23, 1.6e-19, 3.0, 3.1415l, 6.02e23f • Characters – ‘x’, ‘n’ • Strings – "Hello world“, “onentwonthree” • Boolean Values – true, false
  • 10. Operators Level 1 Operator :: Description scope Grouping Left-to-right 2 () [] . -> ++ -- dynamic_cast static_cast reinterpret_cast const_cast typeid postfix Left-to-right 4 ++ -- ~ ! sizeof new delete *& +(type) unary (prefix) indirection and reference (pointers) unary sign operator type casting 5 .* ->* pointer-to-member Left-to-right 6 7 8 9 10 11 12 13 14 15 16 */% +<< >> < > <= >= == != & ^ | && || ?: multiplicative additive shift relational equality bitwise AND bitwise XOR bitwise OR logical AND logical OR conditional Left-to-right Left-to-right Left-to-right Left-to-right Left-to-right Left-to-right Left-to-right Left-to-right Left-to-right Left-to-right Right-to-left 17 = *= /= %= += -= >>= <<= &= ^= |= assignment Right-to-left 18 , comma Left-to-right 3 Right-to-left Right-to-left
  • 11. Operators (Cont’) • Grouping – Left to right • a+b+c – (a + b) + c – Right to left • a += b += c – b=b+c – a=a+b
  • 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;
  • 35. Template (Cont’) – Example template <class myType> myType GetMax (myType a, myType b) { return (a>b?a:b); } int x,y; GetMax <int> (x,y);
  • 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[])
  • 53. Process Programming (Cont’) Exe.c //exe.c #include <sys/types.h> #include <sys/wait.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> char *env_init[] = { "USER=unknown", "PATH=/tmp", NULL}; int main() { pid_t pid; if( (pid = fork()) < 0 ){ printf("fork error"); exit(1); }else if (pid == 0){ //child ///* //specify pathname, specify environment if(execle("/home/starryalley/Desktop/Linux_process_signal/example/echoall", "echoall", "arg1", "arg 2", "my arg 3", (char*)0, env_init) < 0){ printf("execle error"); exit(1); } //*/
  • 54. Process Programming (Cont’) Exe.c /* //specify filename, inherit environment if(execlp("./echoall", "echoall", "only 1 arg", (char*)0) < 0){ printf("execlp error"); exit(1); } */ } if(waitpid(pid, NULL, 0) < 0){ printf("wait error"); exit(1); } }
  • 56. Outline • Thread – Introduction – Identification – Creation – Termination • Thread Synchronization – Mutex
  • 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?
  • 64. Example(Cont’) Print_id.c //print_id.c #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <string.h> #include <pthread.h> pthread_t ntid; void printids( const char* s ) { pid_t pid; pthread_t tid; pid = getpid(); tid = pthread_self(); printf( "%s pid %u tid %u (0x%x)n", s, (unsigned int) pid , (unsigned int) tid, (unsigned int) tid ); }
  • 65. Example(Cont’) Print_id.c void* thr_fn( void* arg ) { printids( "New thread: " ); return ((void*) 0); } int main() { int err = pthread_create( &ntid, NULL, thr_fn, NULL ); if ( 0 != err ) { fprintf( stderr, "can't create thread: %sn", strerror( err ) ); } printids( "main thread:" ); sleep( 1 ); return 0; }
  • 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
  • 70. Example Get_rtnv.c //get_rtnv.c #include <stdio.h> #include <sys/types.h> #include <string.h> #include <pthread.h> void* thr_fn1( void* arg ) { printf( "thread 1 returningn" ); return ((void*) 1); } void* thr_fn2( void* arg ) { printf( "thread 2 returningn" ); return ((void*) 2); }
  • 71. Example(Cont’) Get_rtnv.c int main() { int err; pthread_t tid1, tid2; void* tret; err = pthread_create( &tid1, NULL, thr_fn1, NULL ); if ( 0 != err ) { fprintf( stderr, "Can't create thread 1: %sn", strerror( err ) ); return 1; } err = pthread_create( &tid2, NULL, thr_fn2, NULL ); if ( 0 != err ) { fprintf( stderr, "Can't create thread 2: %sn", strerror( err ) ); return 1; }
  • 72. Get_rtnv.c Example(Cont’) err = pthread_join( tid1, &tret ); if ( 0 != err ) { fprintf( stderr, "Can't join with thread 1: %sn", strerror( err ) ); return 1; } printf( "thread 1 exit code %dn", (int) tret ); err = pthread_join( tid2, &tret ); if ( 0 != err ) { fprintf( stderr, "Can't join with thread 2: %sn", strerror( err ) ); return 1; } printf( "thread 2 exit code %dn", (int) tret ); return 0; }
  • 73. Summary Process Primitive Thread Primitive Description fork pthread_create Create a flow of control exit pthread_exit Exit from an existing flow of control waitpid pthread_join Get exit status from flow of control
  • 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.
  • 75. Thread Synchronization • Solution – Lock the critical sections
  • 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
  • 78. Example Mutex Mutex_cnt.c //mutex_cnt.c #include <stdlib.h> #include <stdio.h> #include <pthread.h> struct foo { int f_count; pthread_mutex_t f_lock; }; struct foo* foo_alloc() { struct foo* fp; if ( (fp = malloc(sizeof( struct foo ))) != NULL ) { fp->f_count = 1; if ( pthread_mutex_init( &fp->f_lock, NULL ) != 0 ) { free( fp ); return (NULL); } } return (fp); }
  • 79. Example Mutex(Cont’) Mutex_cnt.c void foo_hold( struct foo* fp ) { pthread_mutex_lock( &fp->f_lock ); fp->f_count++; pthread_mutex_unlock( &fp->f_lock ); } void foo_rele( struct foo* fp ) { pthread_mutex_lock( &fp->f_lock ); if ( --fp->f_count == 0 ) { pthread_mutex_unlock( &fp->f_lock ); pthread_mutex_destroy( &fp->f_lock ); free( fp ); } else pthread_mutex_unlock( &fp->f_lock ); }
  • 80. Example Mutex(Cont’) Mutex_cnt.c void* thr_fn( void* arg ) { struct foo *fp = (struct foo *)arg; foo_hold(fp); printf("foo count = %dn", fp->f_count); foo_rele(fp); pthread_exit( (void*) 0 ); } int main() { struct foo *fp = foo_alloc(); pthread_t tid1, tid2; int i; pthread_create( &tid1, NULL, thr_fn, fp); pthread_create( &tid2, NULL, thr_fn, fp); pthread_join( tid1, (void*) &i ); pthread_join( tid2, (void*) &i ); foo_rele(fp); return 0; }
  • 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