代码
#include <iostream> // std::cout
#include <atomic> // std::atomic
#include <thread> // std::thread
#include <vector> // std::vector
#include <functional>
#include <algorithm>
#include <mutex>
#include <functional>
#include <sstream>
#include <sys/types.h>
#include <unistd.h>
#include <sys/syscall.h>
class Task
{
public:
void executeThread(std::string command)
{
pid_t x = syscall(__NR_gettid);
std::cout<<"execute thread id:"<< x <<"\n";
std::stringstream ss;
ss << std::this_thread::get_id();
uint64_t threadid = std::stoull(ss.str());
std::cout<<"execute thread id:"<< threadid <<"\n";
std::cout<<"execute thread:" << std::this_thread::get_id() << "\n";
for(int i = 0; i < 5; i++)
{
std::cout << command << " :: " << i << std::endl;
}
int i = 0;
std::cout<<"execute thread input a number!";
std::cin >> i;
}
void startThread(void);
std::thread th2;
std::thread th3;
};
void Task::startThread(void)
{
#if 0
std::thread th1(&Task::executeThread, this, "Thread1");
th1.join(); // Without join(), thread will terminate
#elif 0
th2 = std::thread(&Task::executeThread, this, "Thread2");
th2.join();
#else
th3 = std::thread( std::bind(&Task::executeThread, this, "Thread3") );
th3.join();
#endif
}
int main()
{
pid_t x = syscall(__NR_gettid);
std::cout<<"main thread id:"<< x <<"\n";
std::cout<<"main:" << std::this_thread::get_id() << "\n";
std::stringstream ss;
ss << std::this_thread::get_id();
uint64_t threadid = std::stoull(ss.str());
std::cout<<"main thread id:"<< threadid <<"\n";
Task* taskPtr = new Task();
std::cout << "\ntaskPtr: " << taskPtr << std::endl;
taskPtr->startThread();
int i = 0;
std::cout<<"input a number!";
std::cin >> i;
delete taskPtr;
return 0;
}
编译
g++ -g -Wall -std=c++11 -o task task.cpp -lpthread
结果
root@7f4dc6e8ef5e:/test# ./task
main thread id:6058
main:140158864688960
main thread id:140158864688960
taskPtr: 0x561c5978b280
start thread id:140158864688960
start thread:140158864688960
execute thread id:6059
execute thread id:140158846494464
execute thread:140158846494464
Thread3 :: 0
Thread3 :: 1
Thread3 :: 2
Thread3 :: 3
Thread3 :: 4
查看thread id
root@7f4dc6e8ef5e:/test# ps -Tp 6058
PID SPID TTY TIME CMD
6058 6058 pts/3 00:00:00 task
6058 6059 pts/3 00:00:00 task