C++ process new

82
Brief Review to C++ / Process / Thread 石石石 , 石石石 , 石石石 2009/09/14

description

Brief Review to C++ / Process / Thread

Transcript of C++ process new

Page 1: C++ process new

Brief Review to C++ / Process / Thread

石宗胤 , 周惟中 , 蘇文鈺2009/09/14

Page 2: C++ process new

Outline

• C++• Process• Thread

Page 3: C++ process new

C++

Page 4: C++ process new

A Simple Example

• Hello World#include <iostream>

using namespace std;

int main(){

cout << "Hello! World!\n"; cout << “Hello! C++!\n";

return 0; }

Page 5: C++ process new

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

Page 6: C++ process new

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?

Page 7: C++ process new

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; int a; float mynumber; int a; float mynumber;

int a;float mynumber;

Page 8: C++ process new

TypesName Description Size* Range*

char Character or small integer. 1byte signed: -128 to 127unsigned: 0 to 255

short int (short) Short Integer. 2bytes signed: -32768 to 32767unsigned: 0 to 65535

int Integer. 4bytessigned: -2147483648 to 2147483647unsigned: 0 to 4294967295

long int (long) Long integer. 4bytessigned: -2147483648 to 2147483647unsigned: 0 to 4294967295

bool Boolean value. It can take one of two values: true or false. 1byte 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

Page 9: C++ process new

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“, “one\ntwo\nthree”

• Boolean Values– true, false

Page 10: C++ process new

OperatorsLevel Operator Description Grouping1 :: scope Left-to-right

2 () [] . -> ++ -- dynamic_cast static_cast reinterpret_cast const_cast typeid postfix Left-to-right

3++ -- ~ ! sizeof new delete unary (prefix)

Right-to-left* & indirection and reference (pointers)+ - unary sign operator

4 (type) type casting Right-to-left5 .* ->* pointer-to-member Left-to-right6 * / % multiplicative Left-to-right7 + - additive Left-to-right8 << >> shift Left-to-right9 < > <= >= relational Left-to-right10 == != equality Left-to-right11 & bitwise AND Left-to-right12 ^ bitwise XOR Left-to-right13 | bitwise OR Left-to-right14 && logical AND Left-to-right15 || logical OR Left-to-right16 ?: conditional Right-to-left

17 = *= /= %= += -= >>= <<= &= ^= |= assignment Right-to-left

18 , comma Left-to-right

Page 11: C++ process new

Operators (Cont’)

• Grouping– Left to right

• a + b + c– (a + b) + c

– Right to left• a += b += c

– b = b + c– a = a + b

Page 12: C++ process new

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;

Page 13: C++ process new

Basic Input and Output (Cont’)//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;}

Io.cpp

Page 14: C++ process new

Program Flow Control

• Conditional structure– if, else

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

• Jump statements– break– continue– goto

• The selective structure– switch

Page 15: C++ process new

Program Flow Control (Cont’)//flow.cpp #include <iostream>

using namespace std;

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;

elsecout << "a != b" << endl;

for(int i=0;i<a;i++)sum += i;

cout << "sum = " << sum << endl;

Flow.cpp

Page 16: C++ process new

Program Flow Control (Cont’)while(1){

cout << "c = " << c << endl;

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;

}

Flow.cpp

Page 17: C++ process new

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)

Page 18: C++ process new

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);

Page 19: C++ process new

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

Page 20: C++ process new

Compound Data Types

• Arrays– int a[10]; a[0] == 0;– int b[10][10];

• Character Sequences– char c[] = “test sequence”;

0 1 2a …

Page 21: C++ process new

Compound Data Types (Cont’)• Pointers

– int a = 10;– int *p_a = &a; *p_a == 10;– int **p_p_a = &p_a; **p_p_a == 10;

10

56

104

5652 60

104100 108

a

p_a

p_p_a

Page 22: C++ process new

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;

0 1 2

0 1 2

0

1

.

.

.

.

.

.

b

Page 23: C++ process new

Compound Data Types (Cont’)

• Data Structuresstruct example {

int a;float b;char c[4];

};

example tmp;tmp.a = 10;tmp.b = 3.14;tmp.c[0] = ‘a’;

Page 24: C++ process new

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;

Page 25: C++ process new

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;

}

Page 26: C++ process new

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

Page 27: C++ process new

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.

Page 28: C++ process new

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.

Page 29: C++ process new

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.

Page 30: C++ process new

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); } };

Page 31: C++ process new

Inheritance (Cont’)

• The different access types according to who can access them in the following way

Access public protected privatemembers of the same class yes yes yes

members of derived classes yes yes no

not members yes no no

Page 32: C++ process new

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); } };

Page 33: C++ process new

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); } };

Page 34: C++ process new

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;

Page 35: C++ process new

Template (Cont’)

– Exampletemplate <class myType>myType GetMax (myType a, myType b) {

return (a>b?a:b);}

int x,y;GetMax <int> (x,y);

Page 36: C++ process new

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);

Page 37: C++ process new

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

Page 39: C++ process new

Process

Page 40: C++ process new

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.

Page 41: C++ process new

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.

Page 42: C++ process new

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)

Page 43: C++ process new

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

Page 44: C++ process new

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

Page 45: C++ process new

Process Programming (Cont’)//fork.c#include <sys/types.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h>

int glob = 6;char buf[] = "a write to stdout\n";

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); }

Fork.c

Page 46: C++ process new

Process Programming (Cont’) printf("before fork\n");

if( (pid = fork()) < 0){ printf("fork error"); exit(1); } else if (pid == 0){ //this is child glob++; var++; }else sleep(2); //this is parent

printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var); exit(0);

}

Fork.c

Page 47: C++ process new

Process Programming (Cont’)//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

Forkwice.c

Page 48: C++ process new

Process Programming (Cont’)

//now we're the second child, our parent becomes init sleep(1); printf("second child, parent pid = %d\n", getppid()); exit(0); } //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);

}

Forkwice.c

Page 49: C++ process new

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.

Page 50: C++ process new

Process Programming (Cont’)//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 }

Wait.c

Page 51: C++ process new

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 = %d\n", WEXITSTATUS(status)); else if (WIFSIGNALED(status)) printf("abnormal termination, signal number = %d\n", WTERMSIG(status)); else if (WIFSTOPPED(status)) printf("child stopped, signal number= %d\n", WSTOPSIG(status)); exit(0);

}

Wait.c

Page 52: C++ process new

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[])

Page 53: C++ process new

Process Programming (Cont’)//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); }//*/

Exe.c

Page 54: C++ process new

Process Programming (Cont’)/* //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); }}

Exe.c

Page 55: C++ process new

Thread

Page 56: C++ process new

Outline

• Thread– Introduction– Identification– Creation– Termination

• Thread Synchronization– Mutex

Page 57: C++ process new

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.

Page 58: C++ process new

Benefits

1. Simplify a design that need to deal with asynchronous events.

2. Resource sharing3. Improve SOME program throughput

– E.g. blockable program

4. Improve interactive time

Page 59: C++ process new

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

• Shared– Text of executable program– Program’s global and heap memory– Stacks– File descriptors

Page 60: C++ process new

Thread Standard

• Defined in IEEE POSIX.1-2001• POSIX Thread or pthread• How to detect?

– #ifdef _POSIX_THREADS– sysconf( _SC_THREADS )

Page 61: C++ process new

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()

Page 62: C++ process new

Thread Creation• pthread_create()

• Return error code and don’t set errno when failure• No guarantee on the running order of the threads created and the

threads creating

#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

Page 63: C++ process new

Example

• See print_id.c• -D_REENTRANT –lpthread

Q&A:1. Why sleep( 1 ) is needed?2. Why pthread_self() instrad of ntid?

Page 64: C++ process new

Example(Cont’)//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 );}

Print_id.c

Page 65: C++ process new

Example(Cont’)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: %s\n", strerror( err ) );

}

printids( "main thread:" );sleep( 1 );

return 0;}

Print_id.c

Page 66: C++ process new

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)

Page 67: C++ process new

Thread Termination

• How can a thread exit?1. Voluntary

1. Return from the start routine2. Call pthread_exit

2. Involuntary1. Canceled by another thread in the same process

Page 68: C++ process new

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

Page 69: C++ process new

Thread Termination - Voluntary

• Example– See get_rtnv.c

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

Page 70: C++ process new

Example//get_rtnv.c#include <stdio.h>#include <sys/types.h>#include <string.h>#include <pthread.h>

void* thr_fn1( void* arg ){

printf( "thread 1 returning\n" );return ((void*) 1);

}

void* thr_fn2( void* arg ){

printf( "thread 2 returning\n" );return ((void*) 2);

}

Get_rtnv.c

Page 71: C++ process new

Example(Cont’)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: %s\n", strerror( err ) );return 1;

}

err = pthread_create( &tid2, NULL, thr_fn2, NULL );

if ( 0 != err ) {fprintf( stderr, "Can't create thread 2: %s\n", strerror( err ) );return 1;

}

Get_rtnv.c

Page 72: C++ process new

Example(Cont’)err = pthread_join( tid1, &tret );

if ( 0 != err ) {fprintf( stderr, "Can't join with thread 1: %s\n", strerror( err ) );return 1;

}printf( "thread 1 exit code %d\n", (int) tret );

err = pthread_join( tid2, &tret );

if ( 0 != err ) {fprintf( stderr, "Can't join with thread 2: %s\n", strerror( err ) );return 1;

}

printf( "thread 2 exit code %d\n", (int) tret );return 0;

}

Get_rtnv.c

Page 73: C++ process new

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

Page 74: C++ process new

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.

Page 75: C++ process new

Thread Synchronization

• Solution– Lock the critical sections

Page 76: C++ process new

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_tPTHREAD_MUTEX_INITIALIZERint 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

Page 77: C++ process new

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

Page 78: C++ process new

Example Mutex//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);

}

Mutex_cnt.c

Page 79: C++ process new

Example Mutex(Cont’)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 );}

Mutex_cnt.c

Page 80: C++ process new

Example Mutex(Cont’)void* thr_fn( void* arg ){

struct foo *fp = (struct foo *)arg;

foo_hold(fp);printf("foo count = %d\n", 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_cnt.c

Page 81: C++ process new

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.

Page 82: C++ process new

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