Cpper
C/C++高级工程师 Android高级软件工程师 IT集成工程师 音频工程师 熟悉c,c++,java,c#,py,js,asp等多种语言 程序猿
1.使用pthread的理由
      2个字:简单
2.pthread组件
      thread,
      mutex,     
      condition var
      synchronization
3.线程的终止和产生
小例:
#include <pthread/pthread.h>
#include <stdio.h>
#define NUM_THREADS     5

void *PrintHello(void *threadid)
{
      long tid;
      tid = (long)threadid;
      printf("Hello World! It's me, thread #%ld!\n", tid);
      pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
     pthread_t threads[NUM_THREADS];
     int rc;
     long t;
     for(t=0; t<NUM_THREADS; t++)
     {
          printf("In main: creating thread %ld\n", t);
          rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
          if (rc)
          {
               printf("ERROR; return code from pthread_create() is %d\n", rc);
               exit(-1);
          }
      }
     pthread_exit(NULL);
     return 0;
}

通过pthread_create来创建线程
    其第一个参数为线程id,第二个为线程属性,第三个为线程函数,最后一个为数据参数

那么线程如何终止呢:
1.从运行函数终止
2.调用pthread_exit终止
3.调用pthread_cance
4.进程终止

向线程传递参数
#include <pthread/pthread.h>
#include <stdio.h>
#include <string>
#include <iostream>
#define NUM_THREADS     5

struct Data
{
        std::string name;
};

Data* data_impl;

void *PrintHello(void* data_ptr)
{
         struct Data* data;
         data = (Data*)data_ptr;
         std::cout<<data->name<<std::endl;
         pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
      pthread_t threads[NUM_THREADS];
      data_impl = new Data[NUM_THREADS];
      data_impl[0].name = "T1";
      data_impl[1] .name= "T2";
      data_impl[2] .name= "T3";
      data_impl[3] .name= "T4";
      data_impl[4] .name= "T5";
      for(int t=0; t<NUM_THREADS; t++)
      {
          int rc = pthread_create(&threads[t], NULL, PrintHello,&data_impl[t]);
      }
      pthread_exit(NULL);
      delete []data_impl;
      return 0;
}

其他相关线程库:
1.zthread,
2.opentherad
3.boost therad
4.原生态的平台线程函数

posted on 2010-12-01 14:02 ccsdu2009 阅读(1790) 评论(0)  编辑 收藏 引用

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理