Linux下C++多线程编程演示时遇到的问题
最近公司有关于linux程序的开发,作为新人的我马上去复习下linux,参考的是这篇博客
https://blog.youkuaiyun.com/zgege/article/details/79912418
上面教的是c操作线程,以为用c++没事,结果遇到了很多坑
pthread_cancel函数失效?
功能:取消一个执行中的线程
这是我稍微变过的代码
#include<pthread.h>
#include<unistd.h>
#include<iostream>
using namespace std;
void *runFun(void *data){
while(1){
cout<<"My name is"<<endl;
}
return NULL;
}
int main()
{
pthread_t tid;
void *exitCode;
char *name=static_cast<char*>("张三");I"
pthread_create(&tid,NULL,runFun,NULL);
sleep(1);
pthread_cancel(tid);
pthread_join(tid,&exitCode);
if(exitCode==PTHREAD_CANCELED){
cout<<"pthread_canceled"<<endl;
cout<<tid<<endl;
}else{
cout<<"no exit?"<<endl;
}
return 0;
}
这是结果,居然没停住!!! 说好的取消呢? 不仅没停住,醒来后主线程都退出了
后来在网上找到了原因
https://blog.youkuaiyun.com/qingzhuyuxian/article/details/81019173
于是我在线程执行的代码后加入了 pthread_testcancel(); 方法,并且去掉了那个sleep函数
新代码
#include<pthread.h>
#include<unistd.h>
#include<iostream>
using namespace std;
void *runFun(void *data){
while(1){
cout<<"My name is"<<endl;
pthread_testcancel();
}
return NULL;
}
int main()
{
pthread_t tid;
void *exitCode;
char *name=static_cast<char*>("张三");I"
pthread_create(&tid,NULL,runFun,NULL);
pthread_cancel(tid);
pthread_join(tid,&exitCode);
if(exitCode==PTHREAD_CANCELED){
cout<<"pthread_canceled"<<endl;
cout<<tid<<endl;
}else{
cout<<"no exit?"<<endl;
}
return 0;
}
结果
还是直接退出主线程了,这是怎么回事呢?
后来我测试了很久,发现是进程中的那条输出语句最后面的 endl在搞事
删除之后正常输出了
下面的是最终代码,大家可以都试一下,不知道为什么不能输出endl
如果有哪位大牛知道原因或者有其他解决办法也请不吝赐教~
#include<pthread.h>
#include<unistd.h>
#include<iostream>
using namespace std;
void *runFun(void *data){
while(1){
cout<<"My name is";
pthread_testcancel();
}
return NULL;
}
int main()
{
pthread_t tid;
void *exitCode;
char *name=static_cast<char*>("张三");I"
pthread_create(&tid,NULL,runFun,NULL);
pthread_cancel(tid);
pthread_join(tid,&exitCode);
if(exitCode==PTHREAD_CANCELED){
cout<<"pthread_canceled"<<endl;
cout<<tid<<endl;
}else{
cout<<"no exit?"<<endl;
}
return 0;
}