linux 多线程的学习

发布时间:2016-12-8 20:01:42 编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"linux 多线程的学习",主要涉及到linux 多线程的学习方面的内容,对于linux 多线程的学习感兴趣的同学可以参考一下。

pthread_exit的一个目标是,把一个指针传递给pthread_join函数 pthread_join函数的思路是:通过参数的返回值,将该指针值返回给pthread_join的调用者 #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

上一篇:Image Scaling
下一篇:黑马程序员 java基础————语法基础

相关文章

相关评论