search

1. The three most important synchronization mechanisms of threads

1. Semaphores

2. Mutex locks

3. Condition variables

2. Implement a wrapper class for each of the three synchronization mechanisms

#ifdef LOCKER_H
#define LOCKER_H


#include <pthread.h>
#include <semaphore.h>

/*信号量的封装*/
class sem
{
public:
    sem()
    {
        if( sem_init( &sem_like, 0, 0))
        {
            throw std::exception();
        }
    }

    ~sem()
    {
        sem_destroy( &sem_like);
    }

    bool wait()
    {
        return sem_wait( &sem_like)== 0;
    }

    bool post()
    {
        return sem_post( &sem_like)== 0;
    }

private:
    sem_t sem_like;
}


/*互斥锁的封装*/
class locker
{
public:
    locker()
    {
        if( pthread_mutex_init( &mutex_like,NULL) !=0)
        {
            throw std::exception();
        }
    }

    ~locker()
    {
        pthread_mutex_destroy( &mutex_like);
    }

    bool lock()
    {
        return pthread_mutex_lock( &mutex_like)== 0;
    }

    bool unlock()
    {
        return pthread_mutex_unlock( &mutex_like);
    }
private:
    pthread_mutex_t mutex_like;
}



/*条件变量的封装*/
class cond
{
public:
    cond()
    {
        if( pthread_mutex_init( &mutex_like,NULL)!= 0)
        {
            throw std::exception;
        }

        if( pthread_cond_init( &cond_like, NULL)!= 0)
        {
            //释放对应的互斥锁
            pthread_mutex_destroy( &mutex_like);
            throw std::exception;
        }
    }

    ~cond()
    {
        pthread_mutex_destroy( &mutex_like);
        pthread_cond_destroy( &cond_like);
    }

    bool wait()
    {
        int flag= 0;
        pthread_mutex_lock( &mutex_like);
        flag= pthread_cond_wait( &cond_like, &mutex_like);
        pthread_mutex_unlock( &mutex_like);
        return flag== 0;

    }

    bool signal()
    {
        return pthread_cond_signal( &cond_like)== 0;
    }

private:
    pthread_mutex_t mutex_like;
    pthread_cond_t cond_like;
}

#endif</semaphore.h></pthread.h>

3. Implementation Thread Pool 十 The dynamic creation of threads is very time -consuming. If there is a thread pool, when the user request comes, take a free thread from the thread pool to handle the user's request. After the request is processed, the thread becomes idle and wait for the next time .


There are two core data structures: thread container and request queue


1. Thread container

Here a vector container is used to store the IDs of all threads in the thread pool 2. Request queue


here Use a list container to store all requests, and request processing is in the order of fifo

#ifndef THREADPOOL_H
#define THREADPOOL_H

#include <list>
#include <cstdio>
#include <exception>
#include <pthread.h>
#include "locker.h"

template
class threadpool
{
public:
    threadpool( int thread_number = 8, int max_requests = 10000 );
    ~threadpool();
    bool append( T* request );

private:
    static void* worker( void* arg );
    void run();

private:
    int thread_number_like;//当前线程池中的线程个数
    int max_requests_like;//最大请求数
    //pthread_t* threads_like;
    vector threads_like;//线程容器
    std::list workqueue_like;//请求队列
    locker queuelocker_like;//请求队列的访问互斥锁
    sem queuestat_like;//用于请求队列与空闲线程同步的信号量
    bool stop_like;//结束所有线程,线程池此时没有线程
};

template
threadpool::threadpool( int thread_number, int max_requests ) : 
        m_thread_number( thread_number ), m_max_requests( max_requests ), m_stop( false ), m_threads( NULL )
{
    if( ( thread_number 
threadpool::~threadpool()
{
    stop_like = true;
}

template
bool threadpool::append( T* request )
{
    queuelocker_like.lock();
    if ( workqueue_like.size() > max_requests_like )
    {
        queuelocker_like.unlock();
        return false;
    }
    workqueue_like.push_back( request );
    queuelocker_like.unlock();
    queuestat_like.post();
    return true;
}

template
void* threadpool::worker( void* arg )
{
    threadpool* pool = ( threadpool* )arg;//静态函数要调用动态成员run,必须通过参数arg得到
    pool->run();//线程的执行体
    return pool;
}

template
void threadpool::run()
{
    while ( ! m_stop )
    {
        queuestat_like.wait();
        queuelocker_like.lock();
        if ( workqueue_like.empty() )
        {
            queuelocker_like.unlock();
            continue;
        }
        T* request = workqueue_like.front();
        workqueue_like.pop_front();
        queuelocker_like.unlock();
        if ( ! request )
        {
            continue;
        }
        request->process();//执行当前请求所对应的处理函数
    }
}

#endif</pthread.h></exception></cstdio></list>


Note: 1. In the thread pool model here, each thread corresponds to a request

2. This method ensures the timeliness of user requests processing, the performance requirements for the request processing function are smaller, because this model does not require the request processing process to be non-blocking, because the processing delay of one request will not affect the system's processing of other requests (of course the number of threads must be dynamic Increase).

3. This method is not optimal for high-concurrency servers. A method similar to nginx in which one process responds to multiple user requests is more advantageous. The nginx model has two main advantages: 1. The number of processes is fixed and does not It will take up too much memory because there are many threads or processes at the same time. 2: The number of nginx working processes is generally consistent with the number of CPU cores, and a process can be bound to a core, thus saving the system overhead caused by process switching or thread switching

​​​​​


The above has introduced the implementation of a thread pool, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.


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
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

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

Video Face Swap

Video Face Swap

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

Hot Tools

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.