C++ process new

1,198 views

Published on

Brief Review to C++ / Process / Thread

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,198
On SlideShare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
27
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

C++ process new

  1. 1. Brief Review to C++ / Process / Thread 石宗胤, 周惟中, 蘇文鈺 2009/09/14
  2. 2. Outline • C++ • Process • Thread
  3. 3. C++
  4. 4. A Simple Example • Hello World #include <iostream> using namespace std; int main() { cout << "Hello! World!n"; cout << “Hello! C++!n"; return 0; }
  5. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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
  39. 39. Process
  40. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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); } }
  55. 55. Thread
  56. 56. Outline • Thread – Introduction – Identification – Creation – Termination • Thread Synchronization – Mutex
  57. 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. 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. 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. 60. Thread Standard • Defined in IEEE POSIX.1-2001 • POSIX Thread or pthread • How to detect? – #ifdef _POSIX_THREADS – sysconf( _SC_THREADS )
  61. 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. 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. 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. 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. 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. 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. 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. 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. 69. Thread Termination - Voluntary • Example – See get_rtnv.c • Be careful of your Memory Usage – See get_smem_rtnv.c
  70. 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. 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. 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. 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. 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. 75. Thread Synchronization • Solution – Lock the critical sections
  76. 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. 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. 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. 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. 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. 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. 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

×