#ifndef THREAD_VITO_H
#define THREAD_VITO_H
#ifdef _WIN32
#include<windows.h>
#else
#include <pthread.h>
#endif
class ThreadVito
{
#ifdef _WIN32
typedef unsigned(__stdcall* func)(void*);
#else
typedef void* (* func)(void*);
#endif
public:
ThreadVito(func p);
~ThreadVito();
void join();
private:
#ifdef _WIN32
HANDLE _handle;
DWORD _id;
#else
pthread_t _thread;
#endif
bool _started;
bool _running;
};
#endif
#include "ThreadVito.h"
#include<assert.h>
#ifdef _WIN32
#include<windows.h>
#include<process.h>
#else
#include <pthread.h>
#endif
ThreadVito::ThreadVito(func startHook)
{
#ifdef _WIN32
unsigned int id;
_handle =
reinterpret_cast<HANDLE>(
_beginthreadex(nullptr,
0,
startHook,
this,
0,// 新线程的初始状态,0表示立即执行,CREATE_SUSPENDED表示创建之后挂起
&id));
_id = id;
assert(_handle != (HANDLE)-1L);
if (_handle == 0)
{
}
/*if (SetThreadPriority(_handle, priority) == 0)
{
}*/
#else
pthread_attr_t attr;
int rc = pthread_attr_init(&attr);
if (rc != 0)
{
pthread_attr_destroy(&attr);
}
/*if (stackSize > 0)
{
if (stackSize < PTHREAD_STACK_MIN)
{
stackSize = PTHREAD_STACK_MIN;
}
#ifdef __APPLE__
if (stackSize % 4096 > 0)
{
stackSize = stackSize / 4096 * 4096 + 4096;
}
#endif*/
/* rc = pthread_attr_setstacksize(&attr, stackSize);
if (rc != 0)
{
pthread_attr_destroy(&attr);
}*/
// }
/*
if (realtimeScheduling)
{
rc = pthread_attr_setschedpolicy(&attr, SCHED_RR);
if (rc != 0)
{
}
sched_param param;
param.sched_priority = priority;
rc = pthread_attr_setschedparam(&attr, ¶m);
if (rc != 0)
{
pthread_attr_destroy(&attr);
}
pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED);
}
*/
rc = pthread_create(&_thread, &attr, startHook, this);
pthread_attr_destroy(&attr);
if (rc != 0)
{
}
#endif
_started = true;
_running = true;
}
ThreadVito::~ThreadVito()
{
}
void ThreadVito::join()
{
#ifdef _WIN32
if (_handle == 0)
{
}
DWORD rc = WaitForSingleObjectEx(_handle, INFINITE, true);
if (rc != WAIT_OBJECT_0)
{
}
#else
void* ignore = 0;
int rc = pthread_join(_thread, &ignore);
if (rc != 0)
{
}
#endif
}
#include "MutexVito.h"
#include "ThreadVito.h"
#include<iostream>
#include<thread>
#ifdef _WIN32
#include<windows.h>
#include<process.h>
#else
#include <pthread.h>
#endif
#ifdef _WIN32
unsigned int __stdcall print_block(void* arg)
#else
void* print_block(void* arg)
#endif
{
char c = '$';
int n = 1000;
for (int i = 0; i<n; ++i)
{
std::cout << c;
}
std::cout << '\n';
#ifdef _WIN32
return 0;
#else
return;
#endif
}
void test_thread()
{
ThreadVito th1(print_block);
th1.join();
}
int main()
{
test_thread();
return 0;
}