Cpper
C/C++高级工程师 Android高级软件工程师 IT集成工程师 音频工程师 熟悉c,c++,java,c#,py,js,asp等多种语言 程序猿
线程 Joining and Detaching相关函数4个
pthread_joinpthread_detach

pthread_attr_setdetachstate

pthread_attr_getdetachstate
Joining的作用
Joining是线程同步的方法之一
当且仅当线程被设置为joinable时其可被Joining
一个例子:
#include 
<pthread/pthread.h>
#include 
<stdio.h>
#include 
<stdlib.h>
#include 
<math.h>
#define NUM_THREADS    4

void *BusyWork(void *t)
{
       
int i;
       
long tid;
       
double result=0.0;
       tid 
= (long)t;
       printf(
"Thread %ld starting\n",tid);
       
for (i=0; i<1000000; i++)
       {
             result 
= result + sin(i) * tan(i);
       }
       printf(
"Thread %ld done. Result = %e\n",tid, result);
       pthread_exit((
void*) t);
}

int main (int argc, char *argv[])
{
      pthread_t thread[NUM_THREADS];
      pthread_attr_t attr;
      
int rc;
      
long t;
      
void *status;

      
//! 设置线程属性
      pthread_attr_init(&attr);
      pthread_attr_setdetachstate(
&attr, PTHREAD_CREATE_JOINABLE);

      
for(t=0; t<NUM_THREADS; t++)
      {
            printf(
"Main: creating thread %ld\n", t);
            rc 
= pthread_create(&thread[t], &attr, BusyWork, (void *)t);
            
if (rc)
            {
                    printf(
"ERROR; return code from pthread_create()is %d\n", rc);
                    exit(
-1);
            }
        }

        
//! 销毁线程属性
        pthread_attr_destroy(&attr);
        
for(t=0; t<NUM_THREADS; t++)
        {
               rc 
= pthread_join(thread[t], &status);
               
if (rc)
              {
                      printf(
"ERROR; return code from pthread_join()is %d\n", rc);
                      exit(
-1);
               }
               printf(
"Main: completed join with thread %ld having a status of %ld\n",t,(long)status);
       }

       printf(
"Main: program completed. Exiting.\n");
       pthread_exit(NULL);
}

posted on 2010-12-02 10:15 ccsdu2009 阅读(345) 评论(0)  编辑 收藏 引用

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