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

Feb 06, 2017 pm 01:51 PM

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 (www.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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

C# vs. C  : History, Evolution, and Future Prospects C# vs. C : History, Evolution, and Future Prospects Apr 19, 2025 am 12:07 AM

The history and evolution of C# and C are unique, and the future prospects are also different. 1.C was invented by BjarneStroustrup in 1983 to introduce object-oriented programming into the C language. Its evolution process includes multiple standardizations, such as C 11 introducing auto keywords and lambda expressions, C 20 introducing concepts and coroutines, and will focus on performance and system-level programming in the future. 2.C# was released by Microsoft in 2000. Combining the advantages of C and Java, its evolution focuses on simplicity and productivity. For example, C#2.0 introduced generics and C#5.0 introduced asynchronous programming, which will focus on developers' productivity and cloud computing in the future.

Golang and C  : Concurrency vs. Raw Speed Golang and C : Concurrency vs. Raw Speed Apr 21, 2025 am 12:16 AM

Golang is better than C in concurrency, while C is better than Golang in raw speed. 1) Golang achieves efficient concurrency through goroutine and channel, which is suitable for handling a large number of concurrent tasks. 2)C Through compiler optimization and standard library, it provides high performance close to hardware, suitable for applications that require extreme optimization.

Where to write code in vscode Where to write code in vscode Apr 15, 2025 pm 09:54 PM

Writing code in Visual Studio Code (VSCode) is simple and easy to use. Just install VSCode, create a project, select a language, create a file, write code, save and run it. The advantages of VSCode include cross-platform, free and open source, powerful features, rich extensions, and lightweight and fast.

The Performance Race: Golang vs. C The Performance Race: Golang vs. C Apr 16, 2025 am 12:07 AM

Golang and C each have their own advantages in performance competitions: 1) Golang is suitable for high concurrency and rapid development, and 2) C provides higher performance and fine-grained control. The selection should be based on project requirements and team technology stack.

Golang and C  : The Trade-offs in Performance Golang and C : The Trade-offs in Performance Apr 17, 2025 am 12:18 AM

The performance differences between Golang and C are mainly reflected in memory management, compilation optimization and runtime efficiency. 1) Golang's garbage collection mechanism is convenient but may affect performance, 2) C's manual memory management and compiler optimization are more efficient in recursive computing.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Do you use c in visual studio code Do you use c in visual studio code Apr 15, 2025 pm 08:03 PM

Writing C in VS Code is not only feasible, but also efficient and elegant. The key is to install the excellent C/C extension, which provides functions such as code completion, syntax highlighting, and debugging. VS Code's debugging capabilities help you quickly locate bugs, while printf output is an old-fashioned but effective debugging method. In addition, when dynamic memory allocation, the return value should be checked and memory freed to prevent memory leaks, and debugging these issues is convenient in VS Code. Although VS Code cannot directly help with performance optimization, it provides a good development environment for easy analysis of code performance. Good programming habits, readability and maintainability are also crucial. Anyway, VS Code is

How to use VSCode How to use VSCode Apr 15, 2025 pm 11:21 PM

Visual Studio Code (VSCode) is a cross-platform, open source and free code editor developed by Microsoft. It is known for its lightweight, scalability and support for a wide range of programming languages. To install VSCode, please visit the official website to download and run the installer. When using VSCode, you can create new projects, edit code, debug code, navigate projects, expand VSCode, and manage settings. VSCode is available for Windows, macOS, and Linux, supports multiple programming languages ​​and provides various extensions through Marketplace. Its advantages include lightweight, scalability, extensive language support, rich features and version

See all articles