linux程序设计笔记---pthread

来源:互联网 发布:2017人工智能计算大会 编辑:程序博客网 时间:2024/06/06 13:05

/*
在编译多线程程序的时候,要加上-lpthread选项,指定pthread库。在程序代码中包含线程头文件pthread.h
*/
1,
创建一个线程。
 intpthread_create(pthread_t *pthread_id,const pthread_attr_t *attr,void*(*start_rtn)(void *),void *arg);
 pthread_t *pthread_id:
线程id,有系统自动填充。
 pthread_attr_t*attr
:线程属性,一般情况下为NULL
 void*(*start_rtn)(void*)
:线程执行的函数。该函数的返回值是void类型的指针,函数参数也是void类型的指针,注意:
 
这个函数也可以不传递参数。
 
比如:
 void*create(void *args); //
标准形式。
 void*create(void); //
这个也行。
 void *arg 线程执行函数的参数。
2
,等待线程执行。
 intpthread_join(pthread_t pthread_id,void **args)

 pthread_tpthread_id
:线程的id
 void**args
:线程返回的状态码。
3,退出线程方法有两种:
 
一种是正常退出,可以使用的语句:returnpthread_exit(void*args);
 
二种是正常退出。
 
不可以使用exit_exit,这样不但退出线程,而且会退出整个进程。
4
,获取进程ID
 pthread_tpthread_self(void); 
返回线程id.这个idpthread_creat中的第一个参数的值一样。
5
,清除。
 voidpthread_cleanup_push(void (*rtn)(void *),void *args);
 void(*rtn)(void *)
:指定清除函数。
 void*args
;清除函数的参数。
 
 voidpthread_cleanup_pop(int excute);

 如果在pthread_cleanup_pushpthread_cleanup_pop之间的代码出现退出,不管是正常的pthread_exit退出(return退出不算)
 
还是不正常的退出,就会执行pthread_cleanup_push指定的清除函数。如果之间的代码没有出现退出,只有excute为非零的时候
 
才执行pthread_cleanup_push中指定的清除函数,如果excute为零的话,就不执行指定的清除函数。

例程:

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

#include <pthread.h>



void *thread_function(void *arg);

int run_now = 1;

char message[] = "Hello World";



int main() {

     int res;

    pthread_t a_thread;

    void *thread_result;

    int print_count1 = 0;



    res = pthread_create(&a_thread, NULL, thread_function,(void *)message);

    if (res != 0) {

        perror("Thread creation failed");

        exit(EXIT_FAILURE);

    }



    while(print_count1++ < 20) {

        if (run_now == 1) {

            printf("1");

            run_now = 2;

        } else {

            sleep(1);

        }

    }

     printf("\nWaiting for thread to finish...\n");

    res = pthread_join(a_thread, &thread_result);

    if (res != 0) {

        perror("Thread join failed");

        exit(EXIT_FAILURE);

    }

    printf("Thread joined\n");

    exit(EXIT_SUCCESS);

}



void *thread_function(void *arg) {

    int print_count2 = 0;



    while(print_count2++ < 20) {

        if (run_now == 2) {

            printf("2");

            run_now = 1;

        } else {

            sleep(1);

        }

    }

     sleep(3);

}