pthread_exit的一个目标是,把一个指针传递给pthread_join函数
pthread_join函数的思路是:通过参数的返回值,将该指针值返回给pthread_join的调用者
三:pthread_cancel的使用:
in thread, tid = 140456113821440
四:pthread_detach的使用:
#include<pthread.h>
#include<iostream>
#include<unistd.h>
using namespace std;
void* thread(void* arg){
cout<<(long)arg<<endl;
return (void*)20;
}
int main(){
pthread_t tid;
int err=pthread_create(&tid,NULL,thread,(void*)2);
if(err!=0){
cout<<"create failure"<<endl;
return -1;
}
long* r;
pthread_join(tid,(void**)&r);
cout<<(long)r<<endl;
return 0;
}编译:g++ tt.cc -lpthread#include<pthread.h>
#include<iostream>
#include<unistd.h>
using namespace std;
void *thread(void *arg)
{
cout << "in thread, tid = " << pthread_self() << endl;
long i = 2;
pthread_exit(&i);
return (void *)12;
}
int main()
{
pthread_t tid;
if(pthread_create(&tid, NULL, thread, 0) != 0)
{
cout << "pthread_create error" << endl;
return 0;
}
long *r;
pthread_join(tid, (void**)&r);
cout << r << endl;
cout << *r << endl;
cout << "in main thread, tid = " << pthread_self() << endl;
return 0;
}上述代码中,*r指向了一个不再存在的对象,输出结果为:in thread, tid = 139814095632128
0x7f2901812e88
139814095632128
in main thread, tid = 139814112380736将long i = 2;
pthread_exit(&i);改为pthread_exit(new long(2));in thread, tid = 140514155718400
0x7fcbf80008c0
2
in main thread, tid = 140514172467008三:pthread_cancel的使用:
#include<pthread.h>
#include<iostream>
#include<unistd.h>
using namespace std;
void *thread(void *arg)
{
cout << "in thread, tid = " << pthread_self() << endl;
sleep(2);
return (void *)12;
}
int main()
{
pthread_t tid;
if(pthread_create(&tid, NULL, thread, 0) != 0)
{
cout << "pthread_create error" << endl;
return 0;
}
pthread_cancel(tid);
long *r;
pthread_join(tid, (void**)&r);
cout << PTHREAD_CANCELED << endl;
cout << r << endl;
cout << "in main thread, tid = " << pthread_self() << endl;
return 0;
}执行结果:in thread, tid = 140456113821440
四:pthread_detach的使用:
若pthread_join比pthread_detach先调用,也能获取到退出信息
#include<pthread.h>
#include<iostream>
#include<unistd.h>
#include<errno.h>
using namespace std;
void *thread(void *arg)
{
cout << "in thread, tid = " << pthread_self() << endl;
sleep(2);
pthread_detach(pthread_self());
cout << "nihao" << endl;
return (void *)0;
}
int main()
{
pthread_t tid;
if(pthread_create(&tid, NULL, thread, 0) != 0)
{
cout << "pthread_create error" << endl;
return 0;
}
int *r;
int s = pthread_join(tid, (void **)&r);
if(s == EINVAL)
{
cout << "join error" << endl;
}
else
{
cout << r << endl;
}
cout << "in main thread, tid = " << pthread_self() << endl;
return 0;
}运行结果:in thread, tid = 140355871602432
nihao
0
in main thread, tid = 140355888351040
本文详细介绍了pthread库中的几个关键函数:pthread_exit用于从线程退出并返回一个值;pthread_join用于等待一个线程结束并获取其返回值;pthread_cancel用于取消一个正在运行的线程;而pthread_detach则用于分离线程,使主线程不必等待该线程结束。
4万+

被折叠的 条评论
为什么被折叠?



