pthread 简单模拟 Java runnable 接口
#include <algorithm>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include <thread>
#include <atomic>
#include <pthread.h>
using namespace std;
class Runnable {
private:
pthread_t pt;
// 线程是否启动成功, 即是否joinable
int status;
public:
// 线程启动接口
int start();
// 具体run方法
virtual void run() = 0;
// 析构 join
virtual ~Runnable();
};
Runnable::~Runnable() {
if (status) {
void *retV;
int ret = pthread_join(pt, &retV);
if (ret) {
// log
}
}
}
static void *running(void *r) {
Runnable *rr = reinterpret_cast<Runnable *>(r);
rr->run();
pthread_exit(NULL);
}
int Runnable::start() {
pthread_attr_t pat;
pthread_attr_init(&pat);
pthread_attr_setdetachstate(&pat, PTHREAD_CREATE_JOINABLE);
int ret = pthread_create(&pt, &pat, running, (void *) this);
pthread_attr_destroy(&pat);
if (!ret) {
status = 1;
} else {
// log
status = 0;
}
return ret;
}
class PrintRunnable : public Runnable {
public:
void run() override {
int i = 0;
while (i < 10000) {
cout << "value: " << i << endl;
i++;
}
}
};
class SleepRunnable : public Runnable {
public:
void run() override {
int i = 0;
while (i < 10000) {
i++;
std:
cout << "sleep" << endl;
std::this_thread::sleep_for(std::chrono::microseconds(1));
}
}
};
int main() {
PrintRunnable p;
if (p.start()) {
cout << "thread run error" << endl;
}
SleepRunnable s;
s.start();
std::this_thread::sleep_for(std::chrono::seconds(5));
}