Linux线程
时间:2014-03-27 02:52:58
收藏:0
阅读:568
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); |
参数
第一个参数为指向线程标识符的指针。
第二个参数用来设置线程属性,默认为null.
第三个参数是线程运行函数的起始地址。
最后一个参数是运行函数的参数
函数定义: int pthread_join(pthread_t thread, void **retval);
描述 :
pthread_join()函数,以阻塞的方式等待thread指定的线程结束。当函数返回时,被等待线程的资源被收回。如果进程已经结束,那么该函数会立即返回。并且thread指定的线程必须是joinable的。
参数 :
thread: 线程标识符,即线程ID,标识唯一线程。
retval: 用户定义的指针,用来存储被等待线程的返回值。
返回值 : 0代表成功。 失败,返回的则是错误号线程通过调用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
评论(0)