search
HomeBackend DevelopmentC#.Net TutorialC++ multi-threading framework (1): new starts a thread at once

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; 
 };



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;  
};


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);  
};


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; 
 };


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; 
 };


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);  
              
        }  
}


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

TestThread *a=new TestThread("Thread A");

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
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
C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

C# and .NET: Understanding the Relationship Between the TwoC# and .NET: Understanding the Relationship Between the TwoApr 17, 2025 am 12:07 AM

The relationship between C# and .NET is inseparable, but they are not the same thing. C# is a programming language, while .NET is a development platform. C# is used to write code, compile into .NET's intermediate language (IL), and executed by the .NET runtime (CLR).

The Continued Relevance of C# .NET: A Look at Current UsageThe Continued Relevance of C# .NET: A Look at Current UsageApr 16, 2025 am 12:07 AM

C#.NET is still important because it provides powerful tools and libraries that support multiple application development. 1) C# combines .NET framework to make development efficient and convenient. 2) C#'s type safety and garbage collection mechanism enhance its advantages. 3) .NET provides a cross-platform running environment and rich APIs, improving development flexibility.

From Web to Desktop: The Versatility of C# .NETFrom Web to Desktop: The Versatility of C# .NETApr 15, 2025 am 12:07 AM

C#.NETisversatileforbothwebanddesktopdevelopment.1)Forweb,useASP.NETfordynamicapplications.2)Fordesktop,employWindowsFormsorWPFforrichinterfaces.3)UseXamarinforcross-platformdevelopment,enablingcodesharingacrossWindows,macOS,Linux,andmobiledevices.

C# .NET and the Future: Adapting to New TechnologiesC# .NET and the Future: Adapting to New TechnologiesApr 14, 2025 am 12:06 AM

C# and .NET adapt to the needs of emerging technologies through continuous updates and optimizations. 1) C# 9.0 and .NET5 introduce record type and performance optimization. 2) .NETCore enhances cloud native and containerized support. 3) ASP.NETCore integrates with modern web technologies. 4) ML.NET supports machine learning and artificial intelligence. 5) Asynchronous programming and best practices improve performance.

Is C# .NET Right for You? Evaluating its ApplicabilityIs C# .NET Right for You? Evaluating its ApplicabilityApr 13, 2025 am 12:03 AM

C#.NETissuitableforenterprise-levelapplicationswithintheMicrosoftecosystemduetoitsstrongtyping,richlibraries,androbustperformance.However,itmaynotbeidealforcross-platformdevelopmentorwhenrawspeediscritical,wherelanguageslikeRustorGomightbepreferable.

C# Code within .NET: Exploring the Programming ProcessC# Code within .NET: Exploring the Programming ProcessApr 12, 2025 am 12:02 AM

The programming process of C# in .NET includes the following steps: 1) writing C# code, 2) compiling into an intermediate language (IL), and 3) executing by the .NET runtime (CLR). The advantages of C# in .NET are its modern syntax, powerful type system and tight integration with the .NET framework, suitable for various development scenarios from desktop applications to web services.

C# .NET: Exploring Core Concepts and Programming FundamentalsC# .NET: Exploring Core Concepts and Programming FundamentalsApr 10, 2025 am 09:32 AM

C# is a modern, object-oriented programming language developed by Microsoft and as part of the .NET framework. 1.C# supports object-oriented programming (OOP), including encapsulation, inheritance and polymorphism. 2. Asynchronous programming in C# is implemented through async and await keywords to improve application responsiveness. 3. Use LINQ to process data collections concisely. 4. Common errors include null reference exceptions and index out-of-range exceptions. Debugging skills include using a debugger and exception handling. 5. Performance optimization includes using StringBuilder and avoiding unnecessary packing and unboxing.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download

Atom editor mac version download

The most popular open source editor