C + + multithreaded Framework (1): Start a thread on new

Source: Internet
Author: User
A few years ago wrote a C + + multi-threaded framework, although finished, but one lazy to do a note after the No shadow, recently put the code, ready to send to GitHub, here, and then the framework to summarize it.


Multithreading has always been a common problem in programming, especially in Linux C + +, multi-threaded encapsulation has not been very good, of course, there are a lot of third-party libraries can be used, such as boost, but we sometimes do not need so large library, only need a lightweight thread framework on the line, So I made a, at present only in Linux under the use of, but the design is in accordance with the multi-platform to be compiled, if you need, you can add some of their own classes, turn him into a Windows platform for other platforms, such as Ecos,vxworks and so on.


For multi-threading, what we need is to encapsulate the operating system underlying, let the user write the program more attention to his code logic rather than the logic between the threads, preferably a new class after the start of a thread, the communication between the threads has the corresponding class encapsulation, as long as the call on the line.


Based on these, we define a set of base classes to encapsulate various multithreaded interfaces


The operating system base class, which primarily defines the CreateThread function to create a thread, which is a pure virtual function that inherits from its class needs to implement its functions according to the platform

Class Coperatingsystem  {public      :          Coperatingsystem ();          ~coperatingsystem ();            Virtual  bool CreateThread (cthread *mthread,unsigned long stack_size=8*1024) =0;          virtual void  sleepsec (unsigned long sec) =0;        Protected:          cthread     *p_thread;  };



Line base class, defines the threadentry as the thread's entry, Initializethread to initialize the thread, subclasses can initialize different member variables, Mainloop is pure virtual function, is the main function of the thread, is generally a while loop, Subclasses must implement this virtual function.

Class Cthread  {public      :          cthread (const char *m_thread_name);          ~cthread ();           void Threadentry (Ccountingsem *psemaphore);        Protected:          virtual bool Initializethread ();          virtual void Mainloop () =0;            Coperatingsystem        *p_opration_system;          Char        *p_thread_name;  };


For platform agnostic, a simple factory model is used to return different operating system classes, semaphore classes, and mutex classes based on different platforms.

Class Coperatingsystemfactory  {public      :          static Coperatingsystem *newoperatingsystem ();          Static Ccountingsem  *newcountingsem (unsigned int init);          Static CMutex           *newmutex (const char *pname=null);  };


Semaphore base class, pure virtual function defines the get and post semaphore methods, subclasses must be implemented differently depending on the system type

Class Ccountingsem  {public      :          Ccountingsem ();          ~ccountingsem ();           virtual bool                Get (Mode mode = Kforever, unsigned long Timeoutms = 0) = 0;               virtual bool                Post (void) = 0;  };


Mutex base class, pure virtual function defines lock and unlock two methods, similarly, subclasses must be implemented differently depending on the system type

Class CMutex  {public      :          CMutex (const char *pname = NULL);          ~cmutex ();          virtual bool Lock () =0;          virtual bool UnLock () =0;        Protected:          char       *mutex_name;  };


There is a Msgqueue class, next time said.


With these basic classes, we can start.


The result we want is


The user, the programmer, inherits a thread class from Cthread, such as Ctestthread, and then implements the Mainloop method, so that a thread that does not consider communication is written, Then I just need to new this ctestthread in main.cpp, then the thread starts up and there's no other tedious operation.


To implement such a function, what do the above classes need to call a combination?


First of all, because it is under Linux, all base classes are derived from the corresponding subclass of Linux (Cthread not required, because it is written by the user, Coperatingsystemfactory does not need, because it is an abstract factory), so, We created Clinuxmutex,clinuxoperratingsystem,clinuxcountingsem three sub-classes under Linux and implemented pure virtual functions in the base class in these subclasses.


Then, after we new a ctestthread, we need to generate a clinuxoperratingsystem through the newoperatingsystem of Coperatingsystemfactory, The Clinuxoperratingsystem then calls CreateThread to produce a thread function, and then binds the Ctestthread mainloop to the thread function.


Yes, it's so simple.


Once you have downloaded all the files in GitHub, you only need to write your own thread classes, such as:

Class Testthread:public Cthread  {public      :          testthread (const char *m_name);          ~testthread ();          virtual void Mainloop ();  };  Then implement the Mainloop method:  void Testthread::mainloop ()  {      while (1)          {              printf ("%s:hello world\n", P_ thread_name);                        }  }


Then in main.cpp, call a sentence new to this class:

Testthread *a=new testthread ("Thread a");

OK, everything is done, now running, you can continue to play Hello world.

Similarly, you can also new multiple instances

If you want other features of the thread, you can derive a different class from Cthread, it's easy.

A little more complicated is the thread communication, next time.

The code has not finished finishing, and so on to the completion of the upload to GitHub, probably still need two or three days time.


GitHub Address:

Https://github.com/wyh267/Cplusplus_Thread_Lib

The above is the C + + multithreaded Framework (1): New to start a thread of content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.