C++ProgrammingLecture6AdvancedTopics[C++编程讲座6高级主题课件.ppt

上传人:小飞机 文档编号:2166633 上传时间:2023-01-23 格式:PPT 页数:46 大小:187KB
返回 下载 相关 举报
C++ProgrammingLecture6AdvancedTopics[C++编程讲座6高级主题课件.ppt_第1页
第1页 / 共46页
C++ProgrammingLecture6AdvancedTopics[C++编程讲座6高级主题课件.ppt_第2页
第2页 / 共46页
C++ProgrammingLecture6AdvancedTopics[C++编程讲座6高级主题课件.ppt_第3页
第3页 / 共46页
C++ProgrammingLecture6AdvancedTopics[C++编程讲座6高级主题课件.ppt_第4页
第4页 / 共46页
C++ProgrammingLecture6AdvancedTopics[C++编程讲座6高级主题课件.ppt_第5页
第5页 / 共46页
点击查看更多>>
资源描述

《C++ProgrammingLecture6AdvancedTopics[C++编程讲座6高级主题课件.ppt》由会员分享,可在线阅读,更多相关《C++ProgrammingLecture6AdvancedTopics[C++编程讲座6高级主题课件.ppt(46页珍藏版)》请在三一办公上搜索。

1、EE4E.C+Programming,Lecture 6Advanced Topics,Contents,Introduction Exception handling in C+An object oriented approach to exception handlingtry-catch model of exception handlingException handling exampleRe-throwing exceptionsException specificationsMulti-threadingThread creationThread priorityThread

2、synchronisation,Introduction,We will look at 2 more advanced topics in C+Exception handlingMulti-threading,An object oriented approach to exception handling,Robust C+programs must include exception handlingExceptions are error conditions encountered in executing class methodsAttempting to read past

3、an end of fileAttempting to read a file that doesnt existTrying to open a malformed URLDivide by zeroTaking the square root of a negative numberetc,Normal error handling(in C)would return an error code(eg.1),class myClasspublic:int readFile(.)doif(!end_of_file)/read the fileelsereturn 1;while not_en

4、d_of_file return number_of_bytes_read;,This is a simple sometimes effective method but:Sometimes not possible to return a valid error code.Not object oriented!No information about the error is contained in the error codeApplication code gets polluted with error checking codeIt would be nice to have

5、all of the error handling in one placeThe method might not be able to return normally from the error.An example would be if a resource the method was accessing was not available,The try-catch model of exception handling,Object-oriented applications comprise the use of pre-defined components(objects)

6、by the application and the interaction between these objectsThe object cannot know in advance how the application will process any error conditions it encountersThe try-catch mechanism is a means by which errors in object code can be communicated in a consistent way to the calling application,Applic

7、ation,Object 1,Method call,Error condition,try clause,catch clause,Exception handling example,We will look at a simple example of exception handling involving handling a simple divide by zero errorThe exception handler simply prints out an error messageHowever,the key point is that the program doesn

8、t terminate but allows the user to continue,#include#include class DivideByZeroException:public exceptionpublic:DivideByZeroException:DivideByZeroException():exception(Attempted divide by zero);double quotient(int num,int den)if(den=0)throw DivideByZeroException();return(double)(num)/den;,int main()

9、int number1,number2;double result;cout number1 number2)try result=quotient(number1,number2);cout The quotient is result endl;catch(DivideByZeroException,Key point is the calling of quotient()within the try clausequotient()throws the DivideByZeroException exception using the throw()keyword if a zero

10、denominator is inputThis is then caught in the catch clause immediately after the try clause,Re-throwing exceptions,Often,the exception handler is unable to adequately process the exception For example,it might not be appropriate for the exception to be handled within the object in which the excepti

11、on was generatedTypically,the exception is then re-thrown on to an outer objectIt is possible to have chains of unhandled exceptions re-thrownAt some level,the exception must be handled,main,Object 2,Object 1 throws exception,Calls method of,Calls method of,re-throw,handles exception,re-throw,class

12、MyClass1 public:MyClass1()void aMethod1()trythrow exception();catch(exception,class MyClass2 public:MyClass2()void aMethod2()MyClass1 myObject1;trymyObject1.aMethod1();catch(exception,int main()MyClass2 myObject2;trymyObject2.aMethod2();catch(exception,In this simple example,an exception in generate

13、d in one object,re-thrown in the handler of the calling object and then handled in the main programThe program produces the following output:,Exception thrown in aMethod1Exception re-thrown in aMethod2Exception handled in mainProgram terminates,Exception specifications,An exception specification(a t

14、hrow list)enumerates a list of exceptions that a function can throwIndicates that the function throws exceptions only of types ExceptionA,ExceptionB,ExceptionC If it throws a different type of exception,then function unexpected()is called which normally aborts the program,int aFunction(int arg)throw

15、(ExceptionA,ExceptionB,ExceptionC)/function body),(No exception specification.)Indicates that the function can throw any exception(Empty specification.)Indicates that the function cannot throw an exceptionIf it does,function unexpected()is called,int aFunction(int arg)/function body),int aFunction(i

16、nt arg)throw()/function body),Comparison with JavaException handling almost identical in Java and C+with a few minor syntactic differencesThe main difference is a member function must advertise when it throws an exception in JavaThis function must then be called in a try-catch clause,int aFunction(i

17、nt arg)throws IOException/Java/function body),Multi-threading in C+,We are familiar with the idea of multi-tasking Multi-tasking refers to an operating system running several processes concurrentlyEach process has its own completely independent data Multi-tasking is difficult to incorporate in appli

18、cation programs requiring system programming primitives,However,a single application program can be written as a set of threads which run concurrently(in parallel)A thread is different from a process in that threads share the same dataSwitching between threads involves much less overhead than switch

19、ing between programsSharing data can lead to programming complications(for example in reading/writing databases),C+has direct access to low level API thread functionsIn contrast to Java and C#which has an extra processing layer(within the Thread class)Its ultimately the OS which provides a multithre

20、ading capabilityC+therefore more suited to real-time multi-threading applications,The chief advantage of writing multi-threaded code is efficiencyBetter use is made of the idle time common in all applicationsWaiting for network connectionsWaiting for keyboard input Writing to disk drivesetcA well wr

21、itten application can execute another task during this idle time,A simple C+Thread class,A simple Thread class can easily be developed enabling multi-threaded application to be writtenSimilar in use to the Java Thread classMakes use of Windows Thread functions,class Thread private:string m_strName;p

22、ublic:Thread();Thread(const char*nm);virtual Thread();void setName(const char*nm);string getName()const;void start();virtual void run();void sleep(long ms);void suspend();void resume();void stop();void setPriority(int p);bool wait(const char*m,long ms=5000);void release(const char*m);/Thread priorit

23、iesstatic const int P_HIGHEST;static const int P_LOWEST;static const int P_NORMAL;,As in the case of Java,we must override the virtual run()method for code to execute in a separate thread.Method start()creates a new thread using the windows function CreateThread()and calls the run()methodMethod stop

24、()terminates a threadMethods wait()and release()are for thread synchronisation(see later),Creating a simple multi-threaded application,Class MyThread is a derived class of ThreadThe run()method simply increments a countIndividual threads are identified by a name which is a string passed to the conts

25、ructorA main()program creates 2 threads with 2 different names,#include#include using namespace std;#include ou_thread.husing namespace openutils;class MyThread:public Threadprivate:int m_nCount;public:MyThread(int n,const char*nm)Thread:setName(nm);m_nCount=n;void run()for(int i=0;im_nCount;i+)cout

26、 getName().c_str():i endl;,#include MyThread.hint main()Thread*t1=new MyThread(15,Thread 01);Thread*t2=new MyThread(10,Thread 02);try/Start threadst1-start();t2-start();t1-stop();t2-stop();catch(ThreadException ex)cout ex.getMessage().c_str();delete t1;delete t2;return 0;,Program output:,Thread sync

27、hronization,Each thread pre-empting the other perhaps before a complete line of output is producedProduces a confusing resultEven more serious if the threads are accessing a critical resource such as a database or network connectionThreads can be synchronized using synchronization objects which allo

28、w threads mutually exclusive access to a resource,Unsynchronised threads,Thread 1,Thread 2,Update database,Read database,Pre-empt,Pre-empt,Synchronised threads,Thread 1,Thread 2,Update database,Read database,Windows supports various methods of synchronising multi-threaded codeSemaphoresEvent objects

29、 Mutex objectsMutex objects allow one and only one thread to access a mutex object at any one timeA mutex object is a particular kind of semaphore,The Windows function CreateMutex()is called to create the mutex objectCalled from the Mutex class constructorIn the run()method of MyThread,we must wait

30、for the mutex object to be released by another threadMust remember to release the object once the run()method terminatesAll other methods in MyThread are the same,void MyThread:run()wait(MyMutex);for(int i=0;im_nCount;i+)cout getName().c_str():i endl;release(MyMutex);,int main()Thread*t1=new MyThrea

31、d(15,Thread 01);Thread*t2=new MyThread(10,Thread 02);tryMutex m(MyMutex);t1-start();t2-start();t1-stop();t2-stop();m.release();catch(ThreadException ex)cout ex.getMessage().c_str();delete t1;delete t2;return 0;,Program output:,The second thread waits until the first thread is finishedImportant to ca

32、ll stop()on all threads in the same order start()was calledThe release()function of the Mutex class must be called after the calls to stop(),Thread priority,Windows uses the priority level of a thread to determine how is allocates slices of CPU timeThreads have a base priority level by defaultThe pr

33、iority can be set with the Thread:setPriority()methodThreads are scheduled in a round robin fashion at each priority levelOnly when there are no executable threads at a higher priority level does scheduling at lower priorities take place,int main()Thread*t1=new MyThread(15,Thread 01);Thread*t2=new M

34、yThread(10,Thread 02);tryt1-start();t1-setPriority(Thread:P_LOWEST);t2-start();t2-setPriority(Thread:P_HIGHEST);t1-stop();t2-stop();catch(ThreadException ex)cout ex.getMessage().c_str();delete t1;delete t2;return 0;,Program output,And finally.,We have looked at exception handling and multi-threading

35、 in C+programmingException handling is a crucial feature of writing robust error tolerant codeIts especially important in object oriented programming as exceptions can be passed up the method calling chain and handled by the appropriate objectAlso,in graphical/event handling programs,control is easi

36、ly passed back to the event handling thread following an exception without causing the program to terminate,Writing multi-threaded code can be complexC+differs from Java in that there is no in-built Thread class but it is easy to write one using Windows thread functionsMulti-threading is the basis of many applications and is particularly crucial in graphical/event driven programming as well as real-time systems which control multiple objectsA key feature of multi-threaded code is synchronising access to shared resources and C+has the flexibility to use a range of methods including semaphores,

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 生活休闲 > 在线阅读


备案号:宁ICP备20000045号-2

经营许可证:宁B2-20210002

宁公网安备 64010402000987号