常见手撕代码

线程池Threadpool简单实现

#include <bits/stdc++.h>

using namespace std;

template<typename T>
class threadpool {
public:
    threadpool(int thread_num = 5, int max_request = 10000);
    ~threadpool();
    bool add(T* request);

    static void* worker(void* arg);
    void concreateWork();

private:
    int m_thread_num;
    int m_max_requests;
    pthread_t* m_thread_arr;
    queue<T> m_workqueue;
    bool m_stop;

    locker m_locker;
    sem m_stat;

};

template<typename T>
threadpool<T>::threadpool(int thread_num = 5, int max_request = 10000) 
: m_thread_num(thread_num), m_max_requests(max_request), m_stop(false), m_thread_arr(nullptr) {
    m_thread_arr = new pthread_t[m_thread_num];
    for(int i = 0; i < m_thread_num; i++) {
        //work必须为静态成员函数
        pthread_create(m_thread_arr + i, NULL, worker, this);
        pthread_detach(m_thread_arr[i]);
    }
}

template<typename T>
threadpool<T>::~threadpool() {
    delete[] m_thread_arr;
}

template<typename T>
bool threadpool<T>::add(T* request) {
    m_locker.lock();
    if(m_workqueue.size() > m_max_requests) {
        m_locker.unlock();
        return false;
    }
    m_workqueue.push_back(request);
    m_workqueue.unlock();
    m_stat.post();
    return true;
}

template<typename T>
void* threadpool<T>::worker(void* arg) {
    threadpool* work = (threadpool*) arg;
    work -> concreateWork();
    return work;
}

template<typename T>
void threadpool<T>::run() {
    m_stat.wait();
    m_locker.lock();
    T* cur_request = m_workqueue.front();
    m_workqueue.pop_front();
    m_locker.unlock();

    cur_request->process();
}

//封装互斥锁
class locker {
private:
    pthread_mutex_t m_mutex = PTHREAD_MUTEX_INITIALIZER;
public:
    locker() {
        if(pthread_mutex_init(&mutex, NULL) != 0)
            throw exception();
    }
    ~locker() {
        pthread_mutex_destory(&m_mutex);
    }
    void lock() {
        return pthread_mutex_lock(&m_mutex);
    }
    void unlock() {
        return pthread_mutex_unlock(&m_mutex);
    }
};
//封装信号量
class sem {
private:
    sem_t m_sem;
public:
    sem() {
        sem_init(&m_sem, 0, 0);
    }
    sem(int num) {
        sem_init(&m_sem, 0, num);
    }
    ~sem() {
        sem_destory(&m_sem);
    }
    void post() {
        sem_post(&m_sem);
    }
    void wait() {
        sem_eait(&m_sem);
    }
};

shared_ptr

//存在问题:引用计数不增加

//已解决:重载()函数换成拷贝构造函数

#include <bits/stdc++.h>
using namespace std;

template <class T>
class mShared_ptr {
private:
    T* _ptr;
    int* _refcount;
public:
    mShared_ptr() : _ptr(new T()), _refcount(new int(0)) {}

    mShared_ptr(T* obj) : _ptr(obj), _refcount(new int(1)) {}

    ~mShared_ptr() {
        --(*_refcount);
        if(_ptr && (*_refcount) == 0) {
            delete _ptr;
            delete _refcount;
        }
    }

    mShared_ptr (const mShared_ptr& _other) {
        ++*_other._refcount;
        cout << "_ref : " << *_other._refcount << endl;
        this->_ptr = _other._ptr;
        this->_refcount = _other._refcount;
    }

    mShared_ptr& operator= (const mShared_ptr& _other) {
        if(_other == *this)
            return *this;
        --*(this->_refcount);
        if(this->_ptr && *(this->_refcount) == 0) {
            delete this->_ptr;
            delete this->_refcount;
        }
        ++*_other._refcount;
        cout << "_ref : " << *_other._refcount << endl;
        this->_ptr = _other._ptr;
        this->_refcount = _other._refcount;
        return *this;
    }

    T& operator* () {
        return *_ptr;
    }

    T* operator-> () {
        return _ptr;
    }
    int get_refcount() {
        return *(this->_refcount);
    }

};

int main(int argc, char const *argv[])
{
    mShared_ptr<int> obj(new int(10));
    mShared_ptr<int> obj2 = obj;
    mShared_ptr<int> obj3(obj);

    cout << *obj << endl;
    cout << *obj2 << endl;
    cout << *obj3 << endl;
    cout << obj.get_refcount() << endl;
    cout << obj2.get_refcount() << endl;
    cout << obj3.get_refcount() << endl;
    return 0;
}

String和strcpy函数

//实现string类
#include <bits/stdc++.h>
using namespace std;

class mString {
private:
    char* _data;

public:
    mString(const char* str = nullptr) {
        if(str != nullptr) {
            _data = new char[strlen(str) + 1];
            strcpy(_data, str);
        } else {
            _data = new char[1];
            *_data = '\n';
        }
    }

    mString(const mString& str) {
        _data = new char[strlen(str._data) + 1];
        strcpy(_data, str._data);
    }

    mString& operator= (const mString& str) {
        if(this->_data == str._data) {
            return *this;
        }
        delete[] this->_data;
        this->_data = new char[strlen(str._data) + 1];
        strcpy(this->_data, str._data);
        return *this;
    }

    ~mString() {
        delete[] _data;
    }
    char* data() {
        return this->_data;
    }
};

int main(int argc, char const *argv[])
{
    mString str1("woshinidie");
    mString str2(str1);
    mString str3 = str1;
    for(int i = 0; i < 10; i++) {
        cout << str1.data()[i] << " ";
    }
    cout << endl;
    for(int i = 0; i < 10; i++) {
        cout << str2.data()[i] << " ";
    }
    cout << endl;
    for(int i = 0; i < 10; i++) {
        cout << str3.data()[i] << " ";
    }
    cout << endl;
    return 0;
}
//实现strcpy函数
#include <bits/stdc++.h>
using namespace std;

char* mStrcpy(char* dest, const char* source) {
    if(!dest || !source)
        return nullptr;
    while((*dest++ = *source++) != '\0') {};
    return dest;
}

int main(int argc, char const *argv[])
{
    char s2[20] = "fashdfk";
    char* s1 = new char[strlen(s2) + 1];
    mStrcpy(s1, s2);

    for(int i = 0; i < 20; i++) {
        cout << s1[i] << " ";
    }
    return 0;
}

HashMap不完整实现,大概意思是这样

/*
* @author Bi Wang
* @version 创建时间:2022-3-18
* 说明:本程序实现了一个HashMap。
* 功能:使用开链法解决Hash冲突,实现了查找、插入、删除功能。
*/
#ifndef HASHMAP_H
#define HASHMAP_H


template<class Key, class Value>
class HashNode {
private:
    Key _key;
    Value _value;
    HashNode* next;

public:
    HashNode(Key key, Value Value):_key(key), _value(value), next(nullptr) {
    }
    ~HashNode(){};

    //重载赋值函数
    HashNode& operator=(const HashNode& node) {
        _key = node._key;
        _value = node._value;
        next = node.next;
        return *this;
    }
};

template<class Key, class Value, class HashFunc, class EqualKey>
class HashMap
{
private:
    unsigned int _size;
    HashFunc hash;
    EqualKey equal;
    HashNode<Key, Value> ** hash_table;
    Value valueNUll;
public:
    HashMap(const unsigned int size));
    ~HashMap();
    bool insert(const Key& key, const Value& value);
    bool del(const Key& key);
    Value& find(const Key& key);
};

//构造
template<class Key, class Value, class HashFunc, class EqualKey>
HashMap<Key, Value, HashFunc, EqualKey>::HashMap(const unsigned int size) : 
_size(size), hash(), equal() {
    hash_table = new HashNode<Key, Node>*[_size];
    for(unsigned int i = 0; i < _size; i++) {
        hash_table[i] = nullptr;
    }
}

//析构
template<class Key, class Value, class HashFunc, class EqualKey>
HashMap<Key, Value, HashFunc, EqualKey>::~HashMap() {
    for(unsigned int i = 0; i < _size; i++) {
        HashNode<Key, Value>* cur = hash_table[i];
        while(cur) {
            HashNode<Key, Value>* temp = cur;
            delete temp;
            cur = cur->next;
        }
    }
    delete[] hash_table;
}

//插入
template<class Key, class Value, class HashFunc, class EqualKey>
bool HashMap<Key, Value, HashFunc, EqualKey>::insert(const Key& key, const Value& value) {
    unsigned int index = hash(key)%_size;
    HashNode<Key, Value>* node = new HashNode<Key, Value>(key, value);
    node->next = hash_table[index];
    hash_table[index] = node;
    return true;
}

//删除
template<class Key, class Value, class HashFunc, class EqualKey>
bool HashMap<Key, Value, HashFunc, EqualKey>::del(const Key& key) {
    unsigned int index = hash(key)%_size;
    HashNode<Key, Value>* node = hash_table[index];
    HashNode<Key, Value>* prev = nullptr;
    prev -> next = node;
    while (node) {
        if(node -> _key == key) {
            prev -> next = node -> next;
            delete node;
            return true;
        }
        node = node -> next;
        prev = prev -> next;
    }
    return false;
}

//查找
template<class Key, class Value, class HashFunc, class EqualKey>
Value& HashMap<Key, Value, HashFunc, EqualKey>::find(const Key& key) {
    unsigned int index = hash(key)%_size;
    HashNode<Key, Value>* node = hash_table[index];
    if(!node)   return valueNUll;
    while(node) {
        if(node -> _key == key)
            return node -> _value;
        node = node -> next;
    }
}

//哈希函数
// class HashFunc
// {
// public:
//     int operator()(const unsigned int & key )
//     {
//         int hash = 0;
//         for(int i = 0; i < key.length(); ++i)
//         {
//             hash = hash << 7 ^ key[i];
//         }
//         return (hash & 0x7FFFFFFF);
//     }
// };

//比较函数,上面实现的哈希表默认是数值类型,不需要比较函数
// class EqualKey
// {
// public:
//     bool operator()(const string & A, const string & B)
//     {
//         if (A.compare(B) == 0)
//             return true;
//         else
//             return false;
//     }
// };

#endif
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、C语言基础 1、struct 的内存对齐和填充问题其实只要记住一个概念和三个原则就可以了: 一个概念:自然对齐...
    XDgbh阅读 2,230评论 1 38
  • 目录faster rcnn论文备注caffe代码框架简介faster rcnn代码分析后记 faster rcnn...
    db24cc阅读 9,640评论 2 12
  • 未完每日更新 https://blog.csdn.net/yawdd/article/details/800101...
    Tommmmm阅读 969评论 0 5
  • 1,节流防抖 节流防抖题[https://github.com/Advanced-Frontend/Daily-I...
    MrAlexLee阅读 593评论 0 1
  • 1.C和C++的区别?C++的特性?面向对象编程的好处? 答:c++在c的基础上增添类,C是一个结构化语言,它的重...
    杰伦哎呦哎呦阅读 9,581评论 0 45