模仿boost,用 tls 实现 interrupt 功能
thread.h
[cpp]
#pragma once
#include <windows.h>
#include <functional>
using namespace std;
#include "singleton.h"
#include "locker.h"
namespace thread {
struct thread;
DWORD WINAPI ThreadFunc(void* thrd);
thread* get_current_thread_data();
void interruption_point();
// #define TLS_OUT_OF_INDEXES 0xFFFFFFFF
DWORD current_thread_tls_key = TLS_OUT_OF_INDEXES;
struct tls_alloc_once : public singleton<tls_alloc_once> {
locker lock;
tls_alloc_once() {
lock.lock();
current_thread_tls_key = TlsAlloc();
lock.unlock();
}
};
struct interrupt_exception {};
struct thread_data {
bool interrupted;
typedef function<void()> f_type;
f_type _f;
thread_data() : interrupted(false) {}
template<typename F>
thread_data(F f) : _f(f), interrupted(false) {}
void run() {
if(_f) _f();
}
};
struct thread {
thread_data _data;
HANDLE _h;
DWORD _id;
thread() {}
thread(thread_data data) : _data(data) {}
void start() {
_h = CreateThread(NULL, 0, ThreadFunc, (void*)this, 0, &_id);
}
void join() {
::WaitForSingleObject(_h, INFINITE);
}
void operator=(thread_data data) {
_data = data;
}
void interrupt() {
_data.interrupted = true;
}
};