-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathThreadLibrary.h
108 lines (84 loc) · 2.09 KB
/
ThreadLibrary.h
1
2
3
4
5
6
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#ifndef THREADLIBRARY_H
#define THREADLIBRARY_H
#include <pthread.h>
#include <vector>
#include <functional>
#include <memory>
#include <mutex>
#include <condition_variable>
class ThreadLibrary {
public:
// Method to create and run threads
void createAndRunThreads(int numThreads, std::function<void(int)> task);
// Method to join all threads
void joinAllThreads();
// Mutex class
class Mutex {
public:
Mutex();
~Mutex();
void lock();
void unlock();
pthread_mutex_t* getPthreadMutex();
private:
pthread_mutex_t mutex;
};
//Thread Attributes
class ThreadAttributes {
public:
ThreadAttributes();
~ThreadAttributes();
void setStackSize(size_t size);
void setDetachState(bool detached);
pthread_attr_t* getPthreadAttr();
private:
pthread_attr_t attr;
};
// Lock guard class
class LockGuard {
public:
LockGuard(Mutex& m);
~LockGuard();
private:
Mutex& mutex;
};
//Condition Variable
class ConditionVariable {
public:
ConditionVariable();
~ConditionVariable();
void wait(Mutex& m);
void notify_one();
void notify_all();
private:
pthread_cond_t cond;
};
//Thread Local Storage (TLS)
template <typename T>
class ThreadLocal {
public:
ThreadLocal();
~ThreadLocal();
T& get();
void set(const T& value);
private:
pthread_key_t key;
static void destructor(void* value);
};
private:
struct ThreadData {
int threadId;
std::function<void(int)> task;
ThreadLibrary* library;
};
static void* threadFunction(void* arg);
void signalThreadCompletion();
std::vector<pthread_t> threads;
std::vector<std::unique_ptr<ThreadData>> threadData;
std::mutex mtx;
std::condition_variable cv;
int completedThreads = 0;
int totalThreads = 0;
bool allThreadsCompleted = false; // Flag to avoid spurious wake-ups
};
#endif // THREADLIBRARY_H