linux pthread 小记

来源:互联网 发布:调查问卷统计软件 编辑:程序博客网 时间:2024/06/11 20:11

部分是翻译,部分是转载,但是总体框架是原创

pthread_detach

man pthread_detach:

The  pthread_detach() function marks the thread identified by thread as
       detached.  When a detached thread terminates, its resources  are  auto-
       matically  released  back  to  the  system without the need for another
       thread to join with the terminated thread.

pthread_create

man pthread_create:

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);

pthread_create(&pid_auth_SP2, NULL, &thread_auth_SP2, NULL)

void * thread_auth_SP2(void * arg) pthread_t pid_auth_SP2

传一个参数:

在不断传输数据的时候,会出现for循环都结束了,然后thread才开始执行,那传递给thread的参数就必须是不同的地址,而不能以i为变量

     pthread_t pid[400];     int *t;         int thread_id[400];    for(i=0; i<round; i++)        thread_id[i] = i;     for(i = 0; i < round; i++)     {        t = thread_id + i;        if (pthread_create(&pid[i], NULL, &thread_VSP, (void*)t) != 0)             //printf("can't creat recv thread: %s(errno: %d)\n", strerror(errno), errno);        {            printf("pthread_create vsp %d: %s(errno: %d)\n", i, strerror(errno), errno);                //perror("pthread_create vsp\n");                exit(2);        }     }


int i = 10;

err1 = pthread_create(&thread, NULL, fn, &i);

void fn(void *arg)
{
    int i = *(int *)arg;
    cout<<"i = "<<i<<endl;
    return ((void *)0);
}

传多个参数

首先定义结构体:

struct  parameter{    int size,    int count;    ...};
然后在main函数将这个结构体指针,作为void *形参的实际参数传递
struct parameter arg;
通过如下的方式来调用函数:
pthread_create(&ntid, NULL, fn, &(arg));
函数中需要定义一个parameter类型的结构指针来引用这个参数
void thr_fn(void *arg){    struct parameter *pstru;    pstru = ( struct parameter *) arg;    然后在这个函数中就可以使用指针来使用相应的变量的值了。}

退出

thread里面调用函数,使用return不会退出thread,使用pthread_exit()或exit()会退出。

A single thread can exit in three ways, thereby stopping its flow of control, without
terminating the entire process.
1. The thread can simply return from the start routine. The return value is the
thread’s exit code.
2. The thread can be canceled by another thread in the same process.
3. The thread can call pthread_exit.

If any thread within a process calls exit, _Exit, or _exit, then the entire process
terminates. Similarly, when the default action is to terminate the process, a signal sent
to a thread will terminate the entire process (we’ll talk more about the interactions
between signals and threads in Section 12.8).




0 0
原创粉丝点击