class thread
{
public:
int _num; // 线程的编号
char _buf[64]; // 线程的名字
pthread_t _tid; // 线程的id
};
void *start_routine(void *args)
{
int cnt = 5;
while (cnt--)
{
sleep(1);
thread *_td = static_cast<thread *>(args);
cout << "i am new thread:" << _td->_buf << ":" << _td->_num
<< ":" << _td->_tid << endl;
}
pthread_exit((void*)100);
}
int main()
{
vector<thread *> threads;
for (int i = 1; i <= 10; i++)
{
thread *td = new thread;
td->_num = i;
snprintf(td->_buf, sizeof(td->_buf), "%s-%d", "thread:", i);
pthread_create(&td->_tid, nullptr, start_routine, (void *)td->_buf);
threads.push_back(td);
}
for (int i = 0;i<threads.size()/2;i++)//取消一半的线程
{
pthread_cancel(threads[i]->_tid);
}
for (auto e : threads)//等待
{
void *ret = nullptr;
pthread_join(e->_tid, &ret);
cout << "等待成功"
<< " tid:" << e->_tid << "quit code: " << (long long)(ret) << endl;
delete e;
}
cout << "等待结束" << endl;
return 0;
}
运行结果如下:
可以看到如果取消线程,那线程还是会被等待然后退出,退出码是-1。其实这是一个宏:
六,线程分离
线程分离使用到的函数 int pthread_detach(pthread_t thread)。先来说明一下,新创建的线程默认是joinable的。但是如果我的主线程并不关心当前的线程的返回值,那当前的线程便与我无关。那我的主线程去等待当前的线程便对我的主线程是一种负担。这个时候便可以来进行线程分离。线程的分离方式有两种:1,主线程去分离子线程 2,子线程自己进行分离。
示例代码:
1,主线程进行分离
cpp复制代码
#include<iostream>
#include<pthread.h>
#include<vector>
#include<unistd.h>
using namespace std;
void* Done(void* args)
{
uint64_t i = (uint64_t)args;
string name = "thread_" + to_string(i);
int cnt = 5;
while (cnt--)
{
sleep(1);
cout << name << "running....." << endl;
sleep(3);
}
}
int main()
{
vector<pthread_t> wait;
for (uint64_t i = 1; i <= 4; i++)
{
pthread_t td;
pthread_create(&td, nullptr, Done, (void*)i);//创建线程
wait.push_back(td);
sleep(3);//先休眠三秒,再进行线程分离
pthread_detach(td);//主线程子集分离
}
for(auto e:wait)//等待线程
{
int n = pthread_join(e,nullptr);
cout << n << " " << endl;//打印等待的返回值,0表示成功,其它表示失败。
}
return 0;
}
2,子线程自己主动分离
cpp复制代码
#include <iostream>
#include <pthread.h>
#include <vector>
#include <unistd.h>
using namespace std;
void *Done(void *args)
{
uint64_t i = (uint64_t)args;
string name = "thread_" + to_string(i);
pthread_detach(pthread_self()); // 子线程自己自动分离
int cnt = 5;
while (cnt--)
{
cout << name << "running....." << endl;
sleep(1);
}
}
int main()
{
vector<pthread_t> wait;
for (uint64_t i = 1; i <= 4; i++)
{
pthread_t td;
pthread_create(&td, nullptr, Done, (void *)i); // 创建线程
wait.push_back(td);
}
for (auto e : wait) // 等待线程
{
int n = pthread_join(e, nullptr);
cout << n << " " << endl; // 打印等待的返回值,0表示成功,其它表示失败。
}
return 0;
}