linux 下线程的使用,主要包含以下方法。编译命令 g++ thread.cpp -o thread -lpthread
要用的pthread库
1 | #include <pthread.h> |
1 2 | int pthread_create(pthread_t * thread , const pthread_attr_t *attr,
void *(*start_routine) ( void *), void *arg); |
线程通过调用pthread_exit函数终止执行,就如同进程在结束时调用exit函数一样。这个函数的作用是,终止调用它的线程并返回一个指向某个对象的指针。
#include<iostream> #include<pthread.h> #include<stdlib.h> #include<unistd.h> #include<string.h> using namespace std; char message[]="hello world"; //线程调用函数 void *thread_function(void *argc) { cout<<"it is in thread"<<endl; sleep(3); strcpy(message,"bye"); char *a="the thread it is exit"; pthread_exit((void *)a); } int main() { int res; pthread_t a_thread; void *thread_result; //创建一个线程 res = pthread_create(&a_thread,NULL,thread_function,(void *)message); if(res != 0) { cout<<"it is error"<<endl; exit(-1); } cout<<"waitint for thread exit"<<endl; //等待线程的结束 res = pthread_join(a_thread,&thread_result); if(res != 0) { cout<<"the thread is join failed"<<endl; exit(-1); } cout<<"threa result is"<<(char *)thread_result<<endl; cout<<"message is"<<message<<endl; return 0; }
本文出自 “风清扬song” 博客,请务必保留此出处http://2309998.blog.51cto.com/2299998/1384807
原文:http://2309998.blog.51cto.com/2299998/1384807