Home > Backend Development > C#.Net Tutorial > C++ multi-threading framework (1): new starts a thread at once

C++ multi-threading framework (1): new starts a thread at once

黄舟
Release: 2017-02-06 13:51:29
Original
2091 people have browsed it

I wrote a C++ multi-threading framework a few years ago. Although it was finished, I was too lazy to explain it once and disappeared. I recently sorted out the code and prepared to send it to github. Here, I will Let’s summarize this framework.


Multi-threading has always been a common problem in programming, especially in C++ on Linux. The encapsulation of multi-threading has not been very good. Of course, there are many third-party libraries that can It can be used, such as boost, but sometimes we don’t need such a huge library and just need a lightweight thread framework, so I compiled one myself. It is currently only used under Linux, but when designing It is compiled according to multiple platforms. If you need it, you can add some classes yourself and turn it into a windows platform for other platforms, such as eCos, Vxworks, etc. .


For multi-threading, what we need is to encapsulate the bottom layer of the operating system so that users can pay more attention to his code logic when writing programs rather than the differences between threads. For logic, it is best to start a thread after creating a new class. The communication between threads is also encapsulated by the corresponding class, and it only needs to be called.


Based on these, we defined a set of base classes to encapsulate various multi-threaded interfaces


operations System base class, which mainly defines the createThread function to create threads. This function is a pure virtual function. Classes inherited from it need to implement their 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; 
 };
Copy after login



Thread base class defines threadEntry as the entrance to the thread, initializeThread to initialize the thread, subclasses can initialize different member variables, mainLoop is a pure virtual function, which is the main function of the thread, usually 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;  
};
Copy after login


In order to be platform independent, a simple factory pattern is used to return different operating system classes, semaphore classes and mutual exclusion classes according to different platforms.

class COperatingSystemFactory  
{  
    public:  
        static COperatingSystem *newOperatingSystem();  
        static CCountingSem  *newCountingSem(unsigned int init);  
        static CMutex           *newMutex(const char *pName=NULL);  
};
Copy after login


Semaphore base class, pure virtual function defines get and post semaphore methods, subclasses must implement different implementations according to system type

class CCountingSem  
{  
    public:  
        CCountingSem();  
        ~CCountingSem();  
         virtual bool                Get(Mode mode = kForever, unsigned long timeoutMS = 0) = 0;  
             virtual bool                Post(void) = 0; 
 };
Copy after login


Mutually exclusive base class, pure virtual function defines two methods lock and unlock. Similarly, subclasses must implement different implementations according to the system type

class CMutex  
{  
    public:  
        CMutex(const char *pName = NULL);  
        ~CMutex();  
        virtual bool Lock()=0;  
        virtual bool UnLock()=0;  
  
    protected:  
        char       *mutex_name; 
 };
Copy after login


Another important point is the msgQueue class, which will be discussed next time.


After having these basic classes, we can start.


The result we hope is that


The user, that is, the programmer, inherits a thread of his own from CThread class, such as CTestThread, and then implement the mainLoop method. In this way, a thread that does not consider communication is finished. Then I only need to new the CTestThread in main.cpp, and then the thread will be started without any other cumbersome operations.


#To achieve such a function, what kind of combined calls are needed for the above classes?


First of all, because it is under Linux, all base classes must derive the corresponding subclasses for Linux (CThread is not needed because it is written by the user, and COperatingSystemFactory also No, because it is an abstract factory), so we created three subclasses of CLinuxMutex, CLinuxOperratingSystem, and CLinuxCountingSem under Linux, and implemented the pure virtual functions in the base class in these subclasses.


Next, after we create a new CTestThread, we need to generate a CLinuxOperratingSystem through the newOperatingSystem of COperatingSystemFactory, and then CLinuxOperratingSystem calls createThread to generate a thread function, and then binds the mainLoop of CTestThread to this in thread function.


Yes, it’s that simple


#After downloading all the files in github, you only need to write your Your own thread class, such as:

class TestThread:public CThread  
{  
    public:  
        TestThread(const char *m_name);  
        ~TestThread();  
        virtual void mainLoop();  
};  
//然后实现mainLoop方法:  
void TestThread::mainLoop()  
{  
    while(1)  
        {  
            printf("%s :hello world\n",p_thread_name);  
              
        }  
}
Copy after login


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

TestThread *a=new TestThread("Thread A");
Copy after login

OK, everything is done. Now run it and you can type hello world continuously.

Similarly, you can also new multiple instances

If you want threads with other functions, you can just derive another class from CThread. It is very simple.

The slightly more complicated thing is thread communication, which I will talk about next time.

The code has not been sorted out yet. It will take about two or three days after the sorting is completed and uploaded to github.


github address:

https://github.com/wyh267/Cplusplus_Thread_Lib

The above is the C++ multi-threading framework (1) :new starts the content of a thread at once. For more related content, please pay attention to the PHP Chinese website (m.sbmmt.com)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template