-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLooper.cpp
More file actions
64 lines (48 loc) · 1.22 KB
/
Looper.cpp
File metadata and controls
64 lines (48 loc) · 1.22 KB
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
//
// Created by theo on 5/22/2021.
//
#include "Looper.h"
#include <thread>
#include <atomic>
#include <iostream>
mtl::Looper::Looper() {
mRunning.store(false);
mStopRequest.store(false);
runnablesQ = new Queue();
}
mtl::Looper::~Looper() {
delete runnablesQ;
}
void mtl::Looper::add(mtl::Runnable* item) {
runnablesQ->push(item);
}
void mtl::Looper::stop() {
mStopRequest.store(true);
}
bool mtl::Looper::run() {
try {
mThread = std::thread(&Looper::looperFunction, this);
}catch (...){
return false;
}
return true;
}
void mtl::Looper::looperFunction() {
mRunning.store(true);
while(!mStopRequest.load()){
try {
if(auto item = runnablesQ->pop()){
reinterpret_cast<Runnable*>(item.value())->getFunction()(reinterpret_cast<Runnable*>(item.value())->getArgument());
if(reinterpret_cast<Runnable*>(item.value())->destroyMe()) delete reinterpret_cast<Runnable*>(item.value());
}
}catch(...){}
}
mRunning.store(false);
}
bool mtl::Looper::isRunning() {
return mRunning.load();
}
void mtl::Looper::stopAndJoin() {
mStopRequest.store(true);
if(mThread.joinable()) mThread.join();
}