获取进程/线程ID
#ifdef WIN32
#include "windows.h"
#else
#include "unistd.h"
#endif
#include <thread>
std::thread m_thread = std::thread(&Logic::LogicThreadFunc);
#ifdef WIN32
printf("pid is %d \n", GetCurrentProcessId());
printf("tid is %d \n", GetCurrentThreadId());
#else
printf("pid is %d \n", getpid());
printf("tid is %d %d %d \n", gettid(), std::this_thread::get_id(), m_thread.get_id());
#endif
//C++标准库的获取方法:
#include <thread>
printf("main thread id = 0x%x\n", std::this_thread::get_id());
std::thread::id id = std::this_thread::get_id();
printf("threadid = 0x%x\n"), *(unsigned int*)&id);
linux线程优先级、设置线程名称:
std::thread m_thread = std::thread(&APPCameraAIS::CameraThread, this);
struct sched_param param;
int policy;
//设置线程优先级
param.sched_priority = 15; //数字越大,优先级越高
pthread_setschedparam(m_thread.native_handle(), SCHED_RR, ¶m);
//获取线程优先级,当前线程句柄用:pthread_self()
int rc = pthread_getschedparam(m_thread.native_handle(), &policy, ¶m);
if (rc == 0)
{
printf("APPCameraAIS get thread priority is %d\n", param.sched_priority);
}
else
{
printf("APPCameraAIS get thread error.\n");
}
//设置线程名称
pthread_setname_np(m_thread.native_handle(), "Logic");
std::string name = "Logicccccccccccccc";
pthread_setname_np(pthread_self(), name.substr(0, 15).c_str()); //最大15个字符
#include <sys/prctl.h>
char szThreadName[20];
memset(szThreadName, 0, 20);
prctl(PR_GET_NAME, szThreadName);
prctl(PR_SET_NAME, "mainThread");
线程操作:
ExitThread(3); //正常结束一个线程函数
TerminateThread(handle); //强制结束一个线程函数,不推荐使用的方式
GetExitCodeThread(handle,&dw); //获取线程结束的退出码
SuspendThread(handle); //挂起\暂停\休眠一个线程
ResumeThread(handle); //唤醒一个线程
GetThreadPriority(handle); //获得线程的优先级
SetThreadPriority(handle); //设置线程的优先级
ClosseHandle(handle); //释放线程句柄
//伪代码
hThread = ::CreateThread(NULL,0, ThreadProcIdle, NULL, CREATE_SUSPENDED, &dwThreadIdIdle);
::SetThreadPriority(hThread,THREAD_PRIORITY_IDLE);
::ResumeThread(hThread);