線程

線程創建函數->pthread_creat()

關於值傳遞問題一個例子如下:

#include<stdio.h>
#include<pthread.h>
#include <stdlib.h>
pthread_t ptid;
struct st
{
   char a[10];
   int p;
}st_func;
/*void *func(void *arg)
{
   int j=0;
   j=*(int *)arg;
   printf("i=%d\n",j);
}*/
void *FUNC(void *arg)
{
   struct st st_func1;
   st_func1=*(struct st *)arg;
   printf("%s,%d\n",st_func1.a,st_func1.p);
}
int
main()
{
   //pthread_t ptid;
   //int i=10;
   //pthread_create(&ptid,NULL,&func,&i);
     struct st st_func = {"hello",4};
     //st_func.p=4;
     //st_func.a="hello";
     pthread_create(&ptid,NULL,&FUNC,&st_func);
   sleep(4);
   return 0;
}

線程退出函數->pthread_exit()
關於退出狀態值傳遞-改自《unix環境高級編程》中一個程序。
//#include "apue.h"
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct
structfunc
{
   char a[10];
   int i;
  
}struct_fn2,struct_fn;
//struct_fn2.i=9;
void *
thr_fn1(void *arg)
{
       
 printf("thread 1 returning\n");
       
      
 return((void *)3);
}
void *
thr_fn2(void *arg)
{
 printf("thread 2 exiting\n");
        struct_fn2.i=9;
        /*struct_fn2.a="hello";*/ 
        strcpy(struct_fn2.a,"hello");
 pthread_exit(&struct_fn2);
}
int
main(void)
{
 int   err;
 pthread_t tid1, tid2;
 void  *tret;
        //struct_fn2.i=9;
        //struct
 err = pthread_create(&tid1, NULL, thr_fn1, NULL);
 if (err != 0)
  //err_quit("can't create thread 1: %s\n", strerror(err));
                  printf("can't create thread 1: %s\n", strerror(err));
 err = pthread_create(&tid2, NULL, thr_fn2, NULL);
 if (err != 0)
  //err_quit("can't create thread 2: %s\n", strerror(err));
                  printf("can't create thread 2: %s\n", strerror(err));
 err = pthread_join(tid1, &tret);
 if (err != 0)
  //err_quit("can't join with thread 1: %s\n", strerror(err));
                  printf("can't join with thread 1: %s\n", strerror(err));
 printf("thread 1 exit code %d\n", (int)tret);
       
 err = pthread_join(tid2, &tret);
        struct_fn=*(struct structfunc *)tret;
 if (err != 0)
  //err_quit("can't join with thread 2: %s\n", strerror(err));
                  printf("can't join with thread 2: %s\n", strerror(err));
 printf("thread 2 exit code %d\n", struct_fn.i);
        printf("thread 2 exit code %s\n", struct_fn.a);
        printf("thread 2 exit code %d\n", (*(struct structfunc *)tret).i);
 exit(0);
}


發佈了14 篇原創文章 · 獲贊 6 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章