backend.h 1.34 KB
Newer Older
chenxl's avatar
chenxl committed
1
2
3
4
5
/**
 * @Description  :
 * @Author       : chenht2022
 * @Date         : 2024-07-22 02:03:05
 * @Version      : 1.0.0
chenxl's avatar
chenxl committed
6
 * @LastEditors  : chenht2022
chenxl's avatar
chenxl committed
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 * @LastEditTime : 2024-07-25 10:33:38
 * @Copyright (c) 2024 by KVCache.AI, All Rights Reserved.
 **/
#ifndef CPUINFER_BACKEND_H
#define CPUINFER_BACKEND_H

#include <atomic>
#include <condition_variable>
#include <cstdio>
#include <functional>
#include <mutex>
#include <thread>
#include <vector>

enum ThreadStatus {
    WORKING,
    WAITING,
    EXIT,
};

struct ThreadState {
    std::unique_ptr<std::atomic<ThreadStatus>> status;
    std::unique_ptr<std::atomic<int>> curr;
    int end;
};

class Backend {
chenxl's avatar
chenxl committed
34
  public:
chenxl's avatar
chenxl committed
35
36
37
    Backend(int);
    ~Backend();
    int get_thread_num();
chenxl's avatar
chenxl committed
38
39
40
    void do_work_stealing_job(int, std::function<void(int)>,
                              std::function<void(int)>,
                              std::function<void(int)>);
liam's avatar
liam committed
41
42
43
    #ifdef USE_NUMA
    static thread_local int numa_node;
    #endif
chenxl's avatar
chenxl committed
44
    static thread_local int thread_local_id;
chenxl's avatar
chenxl committed
45

chenxl's avatar
chenxl committed
46
  private:
chenxl's avatar
chenxl committed
47
    int thread_num_;
chenxl's avatar
chenxl committed
48
49
50
51
52
    int max_thread_num_;
    std::vector<ThreadState> thread_state_; // [thread_num]
    std::function<void(int)> init_func_;
    std::function<void(int)> compute_func_;
    std::function<void(int)> finalize_func_;
chenxl's avatar
chenxl committed
53
54
55
56
57
58
    std::vector<std::thread> workers_;

    void process_tasks(int);
    void worker_thread(int);
};
#endif