Chinaunix首页 | 论坛 | 博客
  • 博客访问: 378260
  • 博文数量: 67
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1741
  • 用 户 组: 普通用户
  • 注册时间: 2013-07-21 22:46
文章分类
文章存档

2014年(22)

2013年(45)

分类: C/C++

2014-04-01 10:15:38

linux 下线程的使用,主要包含以下方法。编译命令  g++ thread.cpp  -o thread -lpthread

要用的pthread库


头文件
  
#include
[1]
函数声明
   
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
#include
#include
#include
#include
using namespace std;
char message[]="hello world";
//线程调用函数
void *thread_function(void *argc)
{
        cout<<"it is in thread"<         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"<                 exit(-1);
        }
        cout<<"waitint for thread exit"<       //等待线程的结束
      res = pthread_join(a_thread,&thread_result);
        if(res != 0)
        {
                cout<<"the thread is join failed"<                 exit(-1);
        }
        cout<<"threa result is"<<(char *)thread_result<         cout<<"message is"<         return 0;
}
阅读(2317) | 评论(0) | 转发(0) |
0

上一篇:反射ACL的学习心得

下一篇:NFS共享

给主人留下些什么吧!~~